import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  UntypedFormControl,
  UntypedFormGroup,
  Validators,
} from '@angular/forms';
import { Router, ActivatedRoute } 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 { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';

@Component({
  selector: 'app-forget-password',
  templateUrl: './forget-password.component.html',
  styleUrls: ['./forget-password.component.scss'],
})
export class ForgetPasswordComponent
  extends ComponentBase
  implements BaseForm, OnInit
{
  form!: FormGroup;
  constructor(
    private readonly toastr: ToastrService,
    private readonly router: Router,
    private readonly authService: AuthService,
    private readonly route: ActivatedRoute
  ) {
    super();
  }

  ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.form = new UntypedFormGroup({
      email: new UntypedFormControl(null, [
        Validators.required,
        Validators.email,
      ]),
    });
  }

  onSubmit(): void {
    if (super.submitValidity(this.form)) {
      this.loading = true;
      this.authService
        .ForgetPassword({ email: this.form.get('email')?.value })
        .pipe(takeUntil(this.destroy$))
        .subscribe(
          (response) => {
            this.loading = false;
            this.toastr.success('Successfully !');
            sessionStorage.setItem('userId', response.userId);
            this.router.navigate(['../verify'], { relativeTo: this.route });
          },
          (error) => {
            this.loading = false;
          }
        );
    }
  }
}
