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


@Component({
  selector: 'app-reset-password-modal',
  standalone: true,
  imports: [TranslateModule, ReactiveFormsModule, CommonModule, PasswordHideShowComponent],
  templateUrl: './reset-password-modal.component.html'
})
export class ResetPasswordModalComponent implements OnInit {
  newPasswordType: string = 'password'
  confirmPasswordType: string = 'password'
  @Input() userId!: string;

  resetPasswordForm!: FormGroup;
  @ViewChild('newPasswordPsh') passwordHideShow?:PasswordHideShowComponent
  @ViewChild('confirmPasswordPsh') confirmPasswordHideShow?:PasswordHideShowComponent

  constructor(
    private fb: FormBuilder,
    private httpURIService: HttpURIService,
    private i18nService: I18NService,
    private storageService: StorageService
  ) {}
  togglePasswordType() {
    this.newPasswordType = this.passwordHideShow?.showPassword ? 'password' : 'text';
  }
  toggleConfirmPasswordType() {
    this.confirmPasswordType = this.confirmPasswordHideShow?.showPassword ? 'password' : 'text';
  }
  ngOnInit(): void {
    this.resetPasswordForm = this.fb.group({
      userId: [''],
      newPassword: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20),
        Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).+$/)
      ]],
      confirmPassword: ['', Validators.required]
    }, { validators: this.passwordMatchValidator });
  }

  ngOnChanges(changes: SimpleChanges): void {
  if (changes['userId'] && this.resetPasswordForm) {
    this.resetPasswordForm.reset({
      userId: this.userId,
      newPassword: '',
      confirmPassword: ''
    });

    this.newPasswordType = 'password';
    this.confirmPasswordType = 'password';

    this.passwordHideShow?.reset();
    this.confirmPasswordHideShow?.reset();
  }
}


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

  submit() {
    if (this.resetPasswordForm.invalid) return;

    const payload = {
      userId: this.userId,
      newPassword: this.resetPasswordForm.get('newPassword')?.value,
      porOrgaCode: this.storageService.getItem('POR_ORGACODE')
    };

    this.httpURIService.requestPOST(URIKey.RESET_PASSWORD_URI, payload)
      .subscribe({
        next: (res) => {
          if (!(res instanceof HttpErrorResponse)) {
            this.i18nService.success(SuccessMessages.RESET_PASSWORD_SUCCESS, []);
            this.closeModal();
          }
        }
      });
  }

  closeModal() {
    this.resetPasswordForm.reset();
    this.newPasswordType = 'password';
    this.confirmPasswordType = 'password';

    this.passwordHideShow?.reset();
    this.confirmPasswordHideShow?.reset();

    const modal = document.getElementById('resetPasswordModal');
    modal?.classList.remove('show');
    modal?.setAttribute('aria-hidden', 'true');
    modal!.style.display = 'none';
    document.body.classList.remove('modal-open');
    document.querySelector('.modal-backdrop')?.remove();
  }
}
