import { Component, Input, OnInit, OnChanges, SimpleChanges, Output, EventEmitter, 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, ErrorMessages } 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],
  templateUrl: './reset-password-modal.component.html'
})
export class ResetPasswordModalComponent implements OnInit, OnChanges {
  newPasswordType: string = 'password';
  confirmPasswordType: string = 'password';
  
  @Input() userId: string | null = null;
  @Output() modalClosed = new EventEmitter<void>();
  
  resetPasswordForm!: FormGroup;
  isSubmitting: boolean = false;
  
  @ViewChild('newPasswordPsh') passwordHideShow?: PasswordHideShowComponent;
  @ViewChild('confirmPasswordPsh') confirmPasswordHideShow?: PasswordHideShowComponent;

  constructor(
    private fb: FormBuilder,
    private httpURIService: HttpURIService,
    private i18nService: I18NService,
    private storageService: StorageService
  ) {}

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

  initializeForm(): void {
    this.resetPasswordForm = this.fb.group({
      newPassword: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20),
        Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
      ]],
      confirmPassword: ['', Validators.required]
    }, { 
      validators: this.passwordMatchValidator,
      updateOn: 'blur'
    });

    // Update confirm password validation when new password changes
    this.resetPasswordForm.get('newPassword')?.valueChanges.subscribe(() => {
      this.resetPasswordForm.get('confirmPassword')?.updateValueAndValidity();
    });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['userId'] && this.resetPasswordForm) {
      console.log('ResetPasswordModal: userId changed to:', this.userId);
      
      // Reset the form when userId changes
      this.resetForm();
      
      // Update the form with new userId if needed
      if (this.userId) {
        // You might want to fetch user details here if needed
        console.log('Preparing reset password for user:', this.userId);
      }
    }
  }

  togglePasswordType() {
    this.newPasswordType = this.newPasswordType === 'password' ? 'text' : 'password';
  }

  toggleConfirmPasswordType() {
    this.confirmPasswordType = this.confirmPasswordType === 'password' ? 'text' : 'password';
  }

  passwordMatchValidator(group: AbstractControl): ValidationErrors | null {
    const newPassword = group.get('newPassword')?.value;
    const confirmPassword = group.get('confirmPassword')?.value;
    
    if (!newPassword || !confirmPassword) return null;
    
    // If passwords don't match, set error on confirmPassword field
    if (newPassword !== confirmPassword) {
      group.get('confirmPassword')?.setErrors({ passwordMismatch: true });
      return { passwordMismatch: true };
    } else {
      group.get('confirmPassword')?.setErrors(null);
      return null;
    }
  }

  submit() {
    if (this.resetPasswordForm.invalid || !this.userId) {
      console.error('Form is invalid or no userId available');
      this.resetPasswordForm.markAllAsTouched();
      return;
    }

    console.log('Submitting reset password for userId:', this.userId);
    
    this.isSubmitting = true;

    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: (response) => {
          if (!(response instanceof HttpErrorResponse)) {
            this.i18nService.success(SuccessMessages.RESET_PASSWORD_SUCCESS, []);
            this.closeModal();
          } else {
            this.i18nService.error("ERR_SEC_0007", []);
          }
          this.isSubmitting = false;
        },
        error: (error) => {
          console.error('Error resetting password:', error);
          this.isSubmitting = false;
        }
      });
  }

  resetForm(): void {
    this.resetPasswordForm.reset();
    this.isSubmitting = false;
    this.newPasswordType = 'password';
    this.confirmPasswordType = 'password';

    // Reset password hide/show components
    this.passwordHideShow?.reset();
    this.confirmPasswordHideShow?.reset();

    // Reset form validation state
    Object.keys(this.resetPasswordForm.controls).forEach(key => {
      const control = this.resetPasswordForm.get(key);
      control?.markAsPristine();
      control?.markAsUntouched();
    });
  }

  closeModal() {
    this.resetForm();
    this.modalClosed.emit();
    
    // Remove the modal backdrop and reset modal state
    const modal = document.getElementById('resetPasswordModal');
    if (modal) {
      modal.classList.remove('show');
      modal.setAttribute('aria-hidden', 'true');
      modal.style.display = 'none';
    }
    
    document.body.classList.remove('modal-open');
    const backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) {
      backdrop.remove();
    }
  }
}