import { Component, inject } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';

import { VerifyEmailOtpAction, VerifyNumberOTPAction } from '../../../shared/action/auth.action';
import { Alert } from '../../../shared/components/widgets/alert/alert';
import { Breadcrumb } from '../../../shared/components/widgets/breadcrumb/breadcrumb';
import { Button } from '../../../shared/components/widgets/button/button';
import { IAuthNumberLoginState } from '../../../shared/interface/auth.interface';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { AuthService } from '../../../shared/services/auth.service';

@Component({
  selector: 'app-otp',
  imports: [TranslateModule, ReactiveFormsModule, Breadcrumb, Alert, Button],
  templateUrl: './otp.html',
  styleUrl: './otp.scss',
})
export class Otp {
  public router = inject(Router);
  public store = inject(Store);
  public authService = inject(AuthService);
  public formBuilder = inject(FormBuilder);

  public form: FormGroup;
  public email: string;
  public otpType: string;
  public number: IAuthNumberLoginState;

  public breadcrumb: IBreadcrumb = {
    title: 'OTP',
    items: [{ label: 'OTP', active: true }],
  };

  constructor() {
    this.form = this.formBuilder.group({
      otp: new FormControl('', [Validators.required, Validators.minLength(5)]),
    });
  }

  ngOnInit() {
    this.otpType = this.authService.otpType;
    if (this.otpType === 'email') {
      this.email = this.store.selectSnapshot(state => state.auth.email);
      if (!this.email) {
        void this.router.navigateByUrl('/auth/login');
      }
    } else if (this.otpType === 'number') {
      this.number = this.store.selectSnapshot(state => state.auth.number);
      if (!this.number.phone) {
        void this.router.navigateByUrl('/auth/login');
      }
    } else {
      void this.router.navigateByUrl('/auth/login');
    }
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      var action: any;
      var value;
      if (this.otpType === 'email') {
        value = {
          email: this.email,
          token: this.form.value.otp,
        };
        action = new VerifyEmailOtpAction(value);
      }

      if (this.otpType === 'number') {
        value = {
          phone: this.number.phone,
          country_code: this.number.country_code,
          token: this.form.value.otp,
        };
        action = new VerifyNumberOTPAction(value);
      }

      this.store.dispatch(action).subscribe({
        complete: () => {
          if (this.otpType === 'email') {
            void this.router.navigateByUrl('/auth/update-password');
          } else {
            void this.router.navigateByUrl('/account/dashboard');
          }
        },
      });
    }
  }
}
