import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { BaseForm } from '@core/base/base-form';
import { ComponentBase } from '@core/base/common-base';
import { AuthService } from '@core/services/authentication/auth.service';
import { NgxOtpInputConfig } from 'ngx-otp-input';
import { takeUntil } from 'rxjs';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-verify-otp',
  templateUrl: './verify-otp.component.html',
  styleUrls: ['./verify-otp.component.scss'],
})
export class VerifyOtpComponent
  extends ComponentBase
  implements BaseForm, OnInit
{
  otpInputConfig: NgxOtpInputConfig = {
    otpLength: 4,
  };

  code!: string;

  form!: FormGroup;

  constructor(
    private readonly router: Router,
    private readonly authService: AuthService,
    private readonly toastr: ToastrService
  ) {
    super();
  }

  ngOnInit(): void {}

  initForm(): void {}

  handleFillEvent(event: string): void {
    this.code = event;
  }

  onSubmit(): void {
    if (this.code.length < 4) {
      this.toastr.warning('Please Enter Your OTP !');
      return;
    }

    this.loading = true;
    this.authService
      .SendCode({ userId: sessionStorage.getItem('userId')!, code: this.code })
      .pipe(takeUntil(this.destroy$))
      .subscribe(
        (res) => {
          console.log(res);
          this.router.navigate(['../change-password']);
          this.loading = false;
        },
        (err) => {
          this.loading = false;
        }
      );
  }
}
