import { Component, effect, inject } from '@angular/core';
import { BtnLoadingComponent } from '@app/shared/components/btn-loading/btn-loading.component';
import { FormBuilder, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { AuthFacade } from '@app/adapters/authentification/auth.facade';
import { ActionType } from '@app/domain/action-type.util';

@Component({
  selector: 'app-forgot-password',
  standalone: true,
  imports: [BtnLoadingComponent, FormsModule, ReactiveFormsModule, RouterLink],
  templateUrl: './forgot-password.component.html',
  styleUrl: './forgot-password.component.scss',
})
export class ForgotPasswordComponent {
  private readonly fb = inject(FormBuilder);
  private readonly facade = inject(AuthFacade);
  protected readonly router = inject(Router);

  fpForm = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
  });

  protected readonly loading = this.facade.loading;
  protected readonly error = this.facade.error;

  constructor() {
    let message = '';

    effect(() => {
      if (!this.loading().isLoading) {
        switch (this.loading().action) {
          case ActionType.CREATE:
            if (!this.error().hasError && this.facade.isRequestPasswordSent()) {
              this.router.navigate(['/auth']);
            }
            break;
        }
      }
    });
  }

  onSubmit() {
    if (this.fpForm.invalid) {
      this.fpForm.setErrors({ invalidForm: true });
      return;
    }
    this.facade.sendRequestPasswordReset(this.fpForm.getRawValue().email!);
  }
}
