import { CommonModule } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslateModule } from '@ngx-translate/core';
import { pageSizeOptions } from '../../utils/app.constants';
import { SetupUser } from '../../models/user';
import { FormBuilder, Validators, FormGroup, AbstractControl } from '@angular/forms';
import { ButtonManagementService } from '../../services/button-management.service';
import { StorageService } from '../../shared/services/storage.service';
import { TableFilterPipe } from '../../shared/pipes/table-filter.pipe';
import { URIKey } from '../../utils/uri-enums';
import { HttpErrorResponse, HttpParams } from '@angular/common/http';
import { HttpURIService } from '../../app.http.uri.service';
import { I18NService } from '../../services/i18n.service';
import { SuccessMessages, ErrorMessages } from '../../utils/enums';
import { ResetPasswordModalComponent } from '../reset-password-modal/reset-password-modal.component';
import { PasswordHideShowComponent } from '../../shared/components/password-hide-show/password-hide-show.component';

@Component({
  selector: 'app-setup-user',
  standalone: true,
  imports: [TranslateModule, ReactiveFormsModule, FormsModule, CommonModule, NgSelectModule, TableFilterPipe, ResetPasswordModalComponent, PasswordHideShowComponent],
  templateUrl: './setup-user.component.html',
  styleUrl: './setup-user.component.scss'
})
export class SetupUserComponent implements OnInit {
  userForm!: FormGroup;
  selectedUserIdForEdit: string | null = null; // For edit form
  selectedUserIdForReset: string | null = null; // For reset password modal
  showForm = false;
  showDeleteModal = false;
  userIdToDelete: any = null;
  allItems: SetupUser[] = [];
  currentPage: number = 1;
  pageSizeOptions = pageSizeOptions;
  itemsPerPage: number = 10;
  pagedItems: any[] = [];
  searchText: any = '';
  renewalDataExpanded: boolean = true;
  totalCount: number = 0;
  mode: 'create' | 'edit' = 'create';
  passwordType: string = 'password';
  userSetupDataExpanded: boolean = true;
  buttonPermissions: any;
  isLoading: boolean = false;
  setupUserList: SetupUser[] = [];
  
  // Store original user data for comparison
  originalUserData: SetupUser | null = null;
  
  roleOptions = [
    { label: 'Admin', value: 'ADMIN' },
    { label: 'User', value: 'USER' },
  ];
    @ViewChild('passShowSetupUser') passwordHideShow?: PasswordHideShowComponent;

  constructor(
    private fb: FormBuilder,
    private buttonManagementService: ButtonManagementService,
    private storageService: StorageService,
    private httpService: HttpURIService,
    private i18nService: I18NService
  ) {}

  toggleSetupPass() {
    this.passwordType = this.passwordHideShow?.showPassword ? 'password' : 'text';
  }
  onSearch(value: string): void {
    this.searchText = value;
  }

  totalPages(): number {
    return Math.ceil(this.allItems.length / this.itemsPerPage);
  }

  previousPage(): void {
    if (this.currentPage > 1) {
      this.currentPage--;
    }
  }

  nextPage(): void {
    if (this.currentPage < this.totalPages()) {
      this.currentPage++;
    }
  }

  itemsPerPageChanged(): void {
    this.currentPage = 1;
    this.updatePagedItems();
  }

  // Submit for creating new user
onSubmit() {
  // For create mode, check if password is required
  if (this.mode === 'create') {
    const passwordControl = this.userForm.get('defaultPassword');
    if (!passwordControl?.value) {
      passwordControl?.setErrors({ required: true });
      this.userForm.markAllAsTouched();
      return;
    }
  }
  
  if (this.userForm.invalid) {
    this.userForm.markAllAsTouched();
    return;
  }

  const newUser: SetupUser = {
    userId: this.userForm.value.userId.trim().toLowerCase(),
    userFullname: this.userForm.value.userFullname.trim(),
    email: this.userForm.value.email.trim(),
    role: this.userForm.value.userRole,
    porOrgacode: this.storageService.getItem('POR_ORGACODE'),
    password: this.userForm.value.defaultPassword
  };

  this.isLoading = true;
  this.httpService.requestPOST<SetupUser>(URIKey.CREATE_USER, newUser).subscribe({
    next: (response) => {
      if (!(response instanceof HttpErrorResponse)) {
        this.i18nService.success(SuccessMessages.USER_CREATED_SUCCESS, []);
        this.resetForm();
        this.loadUsersDirect();
      }
      this.isLoading = false;
    },
    error: (error) => {
      console.error('Error creating user:', error);
      this.isLoading = false;
    }
  });
}

  // Update existing user
onUpdate() {
  // Clear any pattern errors if password is empty in edit mode
  const passwordControl = this.userForm.get('defaultPassword');
  if (passwordControl && !passwordControl.value && this.mode === 'edit') {
    passwordControl.setErrors(null); // Clear errors for empty password in edit mode
  }
  
  if (this.userForm.invalid) {
    this.userForm.markAllAsTouched();
    return;
  }

  const updatedUser: any = {
    userId: this.selectedUserIdForEdit,
    userFullname: this.userForm.value.userFullname.trim(),
    email: this.userForm.value.email.trim(),
    role: this.userForm.value.userRole,
    porOrgacode: this.storageService.getItem('POR_ORGACODE')
  };

  // Only include password if it was provided AND is valid
  if (this.userForm.value.defaultPassword && 
      this.userForm.value.defaultPassword.trim() &&
      this.userForm.get('defaultPassword')?.valid) {
    updatedUser.password = this.userForm.value.defaultPassword.trim();
  }

  let params = new HttpParams().set('userId', this.selectedUserIdForEdit!);

  this.isLoading = true;
  this.httpService.requestPUT<SetupUser>(URIKey.UPDATE_USER, updatedUser, undefined, params).subscribe({
    next: (response) => {
      if (!(response instanceof HttpErrorResponse)) {
        this.i18nService.success(SuccessMessages.USER_UPDATED_SUCCESS, []);
        this.resetForm();
        this.loadUsersDirect();
      }
      this.isLoading = false;
    },
    error: (error) => {
      console.error('Error updating user:', error);
      this.isLoading = false;
    }
  });
}
  // Cancel edit mode
  cancelEdit() {
    this.resetForm();
  }

  // Reset form to create mode
  resetForm() {
    this.userForm.reset();
    this.userForm.enable();
    this.mode = 'create';
    this.selectedUserIdForEdit = null;
    this.originalUserData = null;
    
    // Reset form validation state
    Object.keys(this.userForm.controls).forEach(key => {
      const control = this.userForm.get(key);
      control?.markAsPristine();
      control?.markAsUntouched();
    });
  }

  // Check if form has been modified
  isFormDirty(): boolean {
    if (!this.originalUserData || this.mode !== 'edit') {
      return true;
    }

    const currentValues = this.userForm.value;
    
    // Check if any field has changed (excluding password)
    return (
      currentValues.userFullname !== this.originalUserData.userFullname ||
      currentValues.email !== this.originalUserData.email ||
      currentValues.userRole !== this.originalUserData.role ||
      (currentValues.defaultPassword && currentValues.defaultPassword.trim() !== '')
    );
  }

  // Get role label for display
  getRoleLabel(roleValue: string): string {
    const role = this.roleOptions.find(r => r.value === roleValue);
    return role ? role.label : roleValue;
  }

  updatePagedItems(): void {
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = startIndex + this.itemsPerPage;
    this.pagedItems = this.allItems.slice(startIndex, endIndex);
  }

  getButtonPermissions() {
    this.buttonPermissions = this.buttonManagementService.buttonPermissions["setupUser"];
  }

  toggleTableCard(): void {
    this.userSetupDataExpanded = !this.userSetupDataExpanded;
  }

  confirmDelete(userId: string) {
    const confirmed = window.confirm('Are you sure you want to delete this user?');
    if (confirmed) {
      this.onDelete(userId);
    }
  }

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

initializeForm(): void {
  this.userForm = this.fb.group({
    userId: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.pattern('^[a-zA-Z0-9]*$')
    ]],
    userFullname: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(500)
    ]],
    defaultPassword: ['', [
      // For edit mode, password is optional
      // For create mode, handle required validation separately
      this.passwordValidator.bind(this)
    ]],
    email: ['', [Validators.required, Validators.email]],
    userRole: [null, Validators.required]
  });
}

// Custom validator for password
private passwordValidator(control: AbstractControl): { [key: string]: any } | null {
  const value = control.value;
  
  // If empty and we're in edit mode, it's valid (optional)
  if (!value || value.trim() === '') {
    if (this.mode === 'edit') {
      return null; // Password is optional in edit mode
    }
    // For create mode, we'll handle required validation in onSubmit
    return null; // Don't show pattern error for empty field
  }
  
  // If there's a value, check the pattern
  const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
  if (!pattern.test(value)) {
    return { pattern: true };
  }
  
  return null;
}

// Separate validator function
private createPasswordValidator(mode: 'create' | 'edit'): Validators {
  return (control: AbstractControl) => {
    if (mode === 'create' && !control.value) {
      return { required: true };
    }
    return null;
  };
}

  loadUsersDirect(): void {
    this.isLoading = true;
    let params = new HttpParams()
      .set('page', (this.currentPage - 1).toString())
      .set('size', this.itemsPerPage.toString());

    this.httpService.requestGET<any>(URIKey.GET_ALL_USER_URI, params).subscribe({
      next: (response) => {
        if (response && response.content) {
          this.setupUserList = response.content;
          this.totalCount = response.totalElements || response.content.length;
        } else {
          this.setupUserList = response;
        }
        this.allItems = [...this.setupUserList];
        this.updatePagedItems();
        this.isLoading = false;
      },
      error: (err) => {
        console.error('Error fetching users:', err);
        this.allItems = [];
        this.isLoading = false;
      }
    });
  }

  onView(userId: string): void {
    let params = new HttpParams().set('userId', userId);
    this.isLoading = true;
    
    this.httpService.requestGET<SetupUser>(URIKey.GET_USER_BY_ID, params).subscribe({
      next: (response: SetupUser) => {
        // Store original data
        this.originalUserData = { ...response };
        
        // Patch form values
        this.userForm.patchValue({
          userId: response.userId,
          userFullname: response.userFullname,
          email: response.email,
          userRole: response.role,
          defaultPassword: '' // Clear password field for security
        });
        
        // Enable form for editing
        this.userForm.enable();
        
        // Disable userId field (it shouldn't be changed)
        this.userForm.get('userId')?.disable();
        
        // Set the edit userId
        this.selectedUserIdForEdit = userId;
        this.mode = 'edit'; // Set mode to edit
        this.isLoading = false;
        
        // Scroll to form
        this.scrollToForm();
      },
      error: (err) => {
        console.error('Error fetching user:', err)
        this.isLoading = false;
      }
    });
  }

  onDelete(userId: string) {
    let params = new HttpParams().set('userId', userId);
    this.isLoading = true;
    
    this.httpService.requestDELETE<any>(URIKey.DELETE_USER, params).subscribe({
      next: (response) => {
        if (!(response instanceof HttpErrorResponse)) {
          this.i18nService.success(SuccessMessages.USER_DELETE_SUCCESS, []);
          this.loadUsersDirect();
          this.resetForm();
        }
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Error deleting user:', error);
        this.i18nService.error(ErrorMessages.USER_DELETE_FAILED, []);
        this.isLoading = false;
      }
    });
  }

  openResetPasswordModal(userId: string) {
    console.log('Opening reset password modal for userId:', userId);
    this.selectedUserIdForReset = userId;

    // Show the modal
    const modal = document.getElementById('resetPasswordModal');
    if (modal) {
      modal.classList.add('show');
      modal.style.display = 'block';
      document.body.classList.add('modal-open');

      // Add backdrop
      const backdrop = document.createElement('div');
      backdrop.className = 'modal-backdrop fade show';
      document.body.appendChild(backdrop);
      
      // Listen for modal close event
      const closeModal = () => {
        this.closeResetPasswordModal();
      };
      
      // Add click event to backdrop
      backdrop.addEventListener('click', closeModal);
      
      // Add event listener for escape key
      const handleEscape = (event: KeyboardEvent) => {
        if (event.key === 'Escape') {
          closeModal();
        }
      };
      document.addEventListener('keydown', handleEscape);
      
      // Store event listeners for cleanup
      (modal as any).__backdropListener = closeModal;
      (modal as any).__escapeListener = handleEscape;
    }
  }

  // Helper method to scroll to form
  private scrollToForm(): void {
    setTimeout(() => {
      const formElement = document.querySelector('.card.border');
      if (formElement) {
        formElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }, 100);
  }

  closeResetPasswordModal(): void {
    const modal = document.getElementById('resetPasswordModal');
    
    // Remove event listeners
    if (modal) {
      const backdrop = document.querySelector('.modal-backdrop');
      if (backdrop && (modal as any).__backdropListener) {
        backdrop.removeEventListener('click', (modal as any).__backdropListener);
      }
      
      if ((modal as any).__escapeListener) {
        document.removeEventListener('keydown', (modal as any).__escapeListener);
      }
    }
    
    // Hide modal
    if (modal) {
      modal.classList.remove('show');
      modal.style.display = 'none';
    }
    
    // Remove backdrop
    const backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) {
      backdrop.remove();
    }
    
    document.body.classList.remove('modal-open');
    
    // Clear the reset userId
    this.selectedUserIdForReset = null;
  }
}