import { CommonModule } from '@angular/common';
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 { Observable } from 'rxjs';

import { ForgotPassWordAction } 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 { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { IValues } from '../../../shared/interface/setting.interface';
import { IOption } from '../../../shared/interface/theme-option.interface';
import { AuthService } from '../../../shared/services/auth.service';
import { SettingState } from '../../../shared/state/setting.state';
import { ThemeOptionState } from '../../../shared/state/theme-option.state';

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

  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;
  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;

  public form: FormGroup;
  public breadcrumb: IBreadcrumb = {
    title: 'Forgot Password',
    items: [{ label: 'Forgot Password', active: true }],
  };
  public reCaptcha: boolean = true;

  constructor() {
    this.form = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      recaptcha: ['', [Validators.required]],
    });
    this.setting$.subscribe(setting => {
      if (
        (setting?.google_reCaptcha && !setting?.google_reCaptcha?.status) ||
        !setting?.google_reCaptcha
      ) {
        this.form.removeControl('recaptcha');
        this.reCaptcha = false;
      } else {
        this.form.setControl('recaptcha', new FormControl(null, Validators.required));
        this.reCaptcha = true;
      }
    });
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.store.dispatch(new ForgotPassWordAction(this.form.value)).subscribe({
        complete: () => {
          this.authService.otpType = 'email';
          void this.router.navigateByUrl('/auth/otp');
        },
      });
    }
  }
}
