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

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

@Component({
  standalone: true,
  selector: 'user-reset-pwd',
  templateUrl: './resetpwd.component.html',
  imports: [FormsModule, ReactiveFormsModule, NgClass]
})
export class ResetPwdComponent implements OnInit
{
  private readonly router = inject(Router);
  private readonly service = inject(UserService);
  private readonly fnSvc = inject(FunctionService);
  private readonly formBuilder = inject(FormBuilder);
  private readonly alertService = inject(AlertService);

  public resetPwdForm: FormGroup;
  public loading: boolean = false;
  public canSave: boolean = false;
  public submitted: boolean = false;
  public fieldTextType1: boolean = false;
  public fieldTextType2: boolean = false;

  private userId: number = 0;

  constructor()
  {
    const breadcrumbService = inject(BreadcrumbService);
    breadcrumbService.setItems([{ label: 'System Setup' }, { label: 'User Management' }, { label: 'Users', routerLink: ['/users'] }, { label: 'Reset Password', routerLink: ['/resetPwd'] }]);
    if (!this.service.currentUserValue)
    {
      this.router.navigate(['/login']);
      return;
    }

    const navigated = computed(() => this.router.currentNavigation())();
    this.userId = +navigated?.extras?.state?.id;
    this.canSave = this.service.currentUserValue?.moduleIds?.includes('ELIT.1.2.3_1') || this.service.currentUserValue?.moduleIds?.includes('ELIT.1.2.3_2');
  }

  ngOnInit()
  {
    this.resetPwdForm = this.formBuilder.group(
      {
        loginId: '',
        username: '',
        designation: '',
        mobileNo: '',
        emailAddress: '',
        password: ['', Validators.required],
        confirmPassword: ['', Validators.required],
      },
      {
        validators: EqualValidator('password', 'confirmPassword')
      }
    );

    if (this.userId)
    {
      this.service.getUser(this.userId).subscribe(
        {
          next: (resp: any) =>
          {
            this.loading = false;
            if (resp.returnStatus === 200)
            {
              this.userId = resp.userId;
              this.resetPwdForm.patchValue(
                {
                  loginId: resp.loginId,
                  username: resp.userName,
                  designation: resp.designation,
                  mobileNo: resp.mobileNo,
                  emailAddress: resp.emailAddress
                });
            }
            else
            {
              this.alertService.error(resp.returnMessage);
            }
          },
          error: (errorMessage: string) =>
          {
            this.loading = false;
            this.alertService.error(errorMessage);
          }
        });
    }
  }

  public toggleFieldType(controlId): void
  {
    if (controlId === 1)
      this.fieldTextType1 = !this.fieldTextType1;
    else if (controlId === 2)
      this.fieldTextType2 = !this.fieldTextType2;
  }

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

  public onSubmit(): void
  {
    this.submitted = true;
    this.alertService.clear();
    if (this.resetPwdForm.invalid)
      return;

    this.loading = true;

    const newPwd = this.fnSvc.cipherData(this.f.password.value);
    const cnfPwd = this.fnSvc.cipherData(this.f.confirmPassword.value);
    this.service.resetPassword(this.userId, newPwd, cnfPwd).subscribe(
      {
        next: (resp: any) =>
        {
          this.loading = false;
          if (resp.returnStatus === 200)
          {
            this.loading = false;
            this.resetPwdForm.patchValue(
              {
                password: '',
                confirmPassword: '',
              }
            );

            this.alertService.success(resp.returnMessage);
            this.submitted = false;
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.loading = false;
          this.alertService.error(errorMessage);
        }
      });
  }
}
