import { CommonModule } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, ValidationErrors, Validators } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { PasswordHideShowComponent } from '../../shared/components/password-hide-show/password-hide-show.component';
import { HttpURIService } from '../../app.http.uri.service';
import { URIKey } from '../../utils/uri-enums';
import { StorageService } from '../../shared/services/storage.service';
import { I18NService } from '../../services/i18n.service';
import { HttpErrorResponse } from '@angular/common/http';
import { FormConstants, SuccessMessages } from '../../utils/enums';
import { Router } from '@angular/router';
import { AuthenticationService } from '../../services/authenticate.service';


@Component({
  selector: 'app-change-password',
  imports: [TranslateModule, FormsModule, ReactiveFormsModule, CommonModule, PasswordHideShowComponent,],
  templateUrl: './change-password.component.html',
  styleUrl: './change-password.component.scss'
})

export class ChangePasswordComponent implements OnInit{
  isFirstLogin = false;
  firstTimeLoginForm!: FormGroup;
  changePasswordForm!: FormGroup;
  currentLanguage = new FormControl();
  httpService: any;

passwordType: string = 'password';
passwordType1: string = 'password';
passwordType2: string = 'password';

@ViewChild('psh') passwordHideShow?: PasswordHideShowComponent;
@ViewChild('psh1') passwordHideShow1 ?: PasswordHideShowComponent;
@ViewChild('psh2') passwordHideShow2 ?: PasswordHideShowComponent;
constructor(
  private fb: FormBuilder, 
  private httpURIService: HttpURIService, 
  private storageService: StorageService, 
  private i18nService: I18NService, 
  private router: Router,
  private authService: AuthenticationService ){}

 togglePasswordType() {
    this.passwordType = this.passwordHideShow?.showPassword ? 'password' : 'text';
  }
 togglePasswordType1() {
    this.passwordType1 = this.passwordHideShow1?.showPassword ? 'password' : 'text';
  }
 togglePasswordType2() {
    this.passwordType2 = this.passwordHideShow2?.showPassword ? 'password' : 'text';
  }

   ngOnInit(): void { 
     const userStr = this.storageService.getItem('user');
     if (userStr) {
       const user = JSON.parse(userStr);
       this.isFirstLogin = user?.requiresPasswordChange || user?.user?.firstLogin || false;
     }
        
     if (this.isFirstLogin) {
       this.firstTimeLoginForm = this.fb.group({
         oldPassword: ['', Validators.required],
         newPassword: ['', [
           Validators.required,
           Validators.minLength(8),
           Validators.maxLength(20),
           Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
         ]],
         confirmPassword: ['', [
           Validators.required,
           Validators.minLength(8),
           Validators.maxLength(20),
           Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
         ]]
       }, { validators: [
        this.passwordMatchValidator,
        this.oldAndNewPasswordNotSame,] 
      });
     } 
  
  else {
    this.changePasswordForm = this.fb.group({
      oldPassword: ['', Validators.required],
      newPassword: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20),
        Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
      ]
      ],
      confirmPassword: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20),
        Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
      ]
      ]
    }, { validators: [
      this.passwordMatchValidator,
      this.oldAndNewPasswordNotSame,
    ]
    }, 
     );

  }
}

  passwordMatchValidator(group: AbstractControl): ValidationErrors | null {
    const newPassword = group.get('newPassword')?.value;
    const confirmPassword = group.get('confirmPassword')?.value;
    return newPassword === confirmPassword ? null : { passwordMismatch: true };
  }
  
  oldAndNewPasswordNotSame(group: AbstractControl): ValidationErrors | null {
  const oldPassword = group.get('oldPassword')?.value;
  const newPassword = group.get('newPassword')?.value;

  if (!oldPassword || !newPassword) {
    return null;
  }

  return oldPassword === newPassword
    ? { oldAndNewPasswordSame: true }
    : null;
}


  checkIfFirstTimeChangePasswordOrNot(): void {
    try {
      const currentUser: any = JSON.parse(
        this.storageService.getItem('user') || '{}'
      );

      this.isFirstLogin = !!currentUser?.user?.isFirstLogin;
    } catch (error) {
      console.error('Error parsing user data:', error);
      this.isFirstLogin = false;
    }
  }

 getFormPayload() {
  const form = this.isFirstLogin ? this.firstTimeLoginForm : this.changePasswordForm;
  
  return {
    oldPassword: form.get('oldPassword')?.value || null,
    newPassword: form.get('newPassword')?.value,
    userId: this.storageService.getItem('USER_ID'),
    porOrgaCode: this.storageService.getItem('POR_ORGACODE')
  };
}
  onSubmit(){
    if (this.isFirstLogin) {
      this.changeFirstTimePassword();
    } else {
      this.changeRegularPassword();
    }
  }

  changeFirstTimePassword() {
     if (!this.firstTimeLoginForm || this.firstTimeLoginForm.invalid) {
        if (this.firstTimeLoginForm) {
            this.markFormGroupTouched(this.firstTimeLoginForm);
        }
        return;
    }


    const payload = this.getFormPayload();

    this.httpURIService.requestPOST(URIKey.FIRST_LOGIN_URI, payload)
      .subscribe({
        next: (response) => {
          if (!(response instanceof HttpErrorResponse)) {
            this.i18nService.success(SuccessMessages.CHANGE_PASSWORD_SUCCESS, []);
            this.authService.logout();
            this.router.navigate(['login']);
          }
        },
        error: (error) => {
          console.error('Password change failed:', error);
        }
      });
  }

  changeRegularPassword() {
    if (!this.changePasswordForm || this.changePasswordForm.invalid) {
        if (this.changePasswordForm) {
            this.markFormGroupTouched(this.changePasswordForm);
        }
        return;
    }

    const payload = this.getFormPayload();

    this.httpURIService.requestPOST(URIKey.CHANGE_PASSWORD_URI, payload)
      .subscribe({
        next: (response) => {
          if (!(response instanceof HttpErrorResponse)) {
            this.i18nService.success(SuccessMessages.CHANGE_PASSWORD_SUCCESS, []);
            this.router.navigate(['/home/dashboard']);
          }
        }
      });
  }

  private markFormGroupTouched(formGroup: FormGroup) {
    Object.values(formGroup.controls).forEach(control => {
      control.markAsTouched();
      if (control instanceof FormGroup) {
        this.markFormGroupTouched(control);
      }
    });
  }

}
