import { NgClass} from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AlertService } from '../components/alert';
import { BreadcrumbService } from '../breadcrumb.service';
import { UserService } from '../../providers/user/user.service.';
import { FunctionService } from '../components/models/function.service';

@Component({
  standalone: true,
  selector: 'forgot-password',
  templateUrl: './forgotpassword.component.html',
  imports: [FormsModule, ReactiveFormsModule, NgClass]
})
export class ForgotPasswordComponent implements OnInit
{
  private readonly service = inject(UserService);
  private readonly fnSvc = inject(FunctionService);
  private readonly formBuilder = inject(FormBuilder);
  private readonly alertService = inject(AlertService);

  public forgotPwdForm: FormGroup;
  public loading: boolean = false;
  public submitted: boolean = false;
  public accountValid: boolean = false;

  private userId: number = 0;
  private mobileNo: string = '';
  private emailAddress: string = '';

  constructor()
  {
    const bcSvc = inject(BreadcrumbService);
    bcSvc.setItems([{ label: 'Login', routerLink: ['/login'] }, { label: 'Forgot Password', routerLink: ['/forgotPassword'] }]);
  }

  ngOnInit()
  {
    this.forgotPwdForm = this.formBuilder.group(
      {
        accountId: ['', Validators.required],
        mobileNo: '',
        emailAddress: ''
      });
  }

  get f() { return this.forgotPwdForm.controls; }

  public clearData(): void
  {
    this.userId = 0;
    this.accountValid = false;
    this.emailAddress = this.mobileNo = '';
    this.forgotPwdForm.patchValue({ mobileNo: '', emailAddress: '' });
  }

  public findAccount(): void
  {
    this.submitted = true;
    this.alertService.clear();
    if (this.f.accountId.invalid)
      return;

    this.clearData();
    this.loading = true;
    this.service.findAccount(this.fnSvc.cipherData(this.f.accountId.value),).subscribe(
      {
        next: (resp: any) =>
        {
          this.loading = false;
          if (resp.returnStatus === 200 && resp.value)
          {
            this.submitted = false;
            this.accountValid = true;

            this.userId = resp.userId;
            this.mobileNo = resp.phoneNo;
            this.emailAddress = resp.emailAddress;
            this.forgotPwdForm.patchValue({ mobileNo: resp.phoneNoMasked, emailAddress: resp.emailAddressMasked });
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.loading = false;
          this.alertService.error(errorMessage);
        }
      });
  }

  public sendPassword(): void
  {
    this.submitted = true;
    this.alertService.clear();
    if (!this.userId || this.userId == 0 || (!this.emailAddress && !this.mobileNo))
    {
      this.alertService.error('There is no valid data to send.');
      return;
    }

    this.loading = true;
    const params: any =
    {
      userId: this.fnSvc.cipherData(`${this.userId}`),
      mobileNo: this.fnSvc.cipherData(this.mobileNo),
      emailAddress: this.fnSvc.cipherData(this.emailAddress),
    };
    this.service.sendPassword(params).subscribe(
      {
        next: (resp: any) =>
        {
          this.loading = false;
          if (resp.returnStatus === 200)
          {
            this.loading = false;
            this.alertService.success(resp.returnMessage);
            this.submitted = false;
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.loading = false;
          this.alertService.error(errorMessage);
        }
      });
  }
}
