import { Component, inject, OnInit, TemplateRef, ViewChild, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbNavModule, NgbModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { Subject, takeUntil } from 'rxjs';

import { HubUsersService } from './hub-users.service';
import { RoleManagementService } from '@core/services/hub-users-roles-management.service';
import { AuthService } from '@core/services/auth.service';
import { PageTitle } from '@app/components/page-title/page-title';
import { HubUsersList } from './hub-users-list/hub-users-list';
import { HubUserProfile } from './hub-users-profile/hub-users-profile';

import { 
  ResetPasswordDto,
  UserRole,
  UserType
} from '@core/models/dcb-bo-hub-user.model';

@Component({
  selector: 'app-hub-users',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    NgbNavModule,
    NgbModalModule,
    PageTitle,
    HubUsersList,
    HubUserProfile
  ],
  templateUrl: './hub-users.html',
})
export class HubUsersManagement implements OnInit, OnDestroy {
  private modalService = inject(NgbModal);
  private authService = inject(AuthService);
  private hubUsersService = inject(HubUsersService);
  protected roleService = inject(RoleManagementService);
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();

  // Configuration
  readonly UserRole = UserRole;
  
  // Propriétés de configuration
  pageTitle: string = 'Gestion des Utilisateurs Hub';
  pageSubtitle: string = 'Administrez les utilisateurs de la plateforme DCB';
  badge: any = { icon: 'lucideUsers', text: 'Hub Users' };

  // État de l'interface
  activeTab: 'list' | 'profile' = 'list';
  selectedUserId: string | null = null;

  // Gestion des permissions
  currentUserRole: UserRole | null = null;
  userPermissions: any = null;
  canCreateUsers = false;
  canDeleteUsers = false;
  canManageRoles = false;

  // Formulaire de création
  newUser: {
    username: string;
    email: string;
    firstName: string;
    lastName: string;
    password: string;
    role: UserRole;
    enabled: boolean;
    emailVerified: boolean;
    userType: UserType
  } = this.getDefaultUserForm();

  // États des opérations
  creatingUser = false;
  createUserError = '';
  resettingPassword = false;
  resetPasswordError = '';
  resetPasswordSuccess = '';

  newPassword = '';
  temporaryPassword = false;

  deletingUser = false;
  deleteUserError = '';

  selectedUserForReset: any = null;
  selectedUserForDelete: any = null;

  // UX améliorations
  showPassword = false;
  showNewPassword = false;

  // Références aux templates de modals
  @ViewChild('createUserModal') createUserModal!: TemplateRef<any>;
  @ViewChild('resetPasswordModal') resetPasswordModal!: TemplateRef<any>;
  @ViewChild('deleteUserModal') deleteUserModal!: TemplateRef<any>;

  // Références aux composants enfants
  @ViewChild(HubUsersList) hubUsersList!: HubUsersList;

  // Rôles disponibles
  availableRoles: { value: UserRole; label: string; description: string }[] = [];
  assignableRoles: UserRole[] = [];

  ngOnInit() {
    this.activeTab = 'list';
    this.loadCurrentUserPermissions();
    this.loadAvailableRoles();
    this.newUser.role = UserRole.DCB_SUPPORT;
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  /**
   * Initialise les permissions de l'utilisateur courant
   */
  private loadCurrentUserPermissions(): void {
    this.authService.getUserProfile()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.currentUserRole = this.extractUserRole(user);

          console.log(`HUB User ROLE: ${this.currentUserRole}`);

          if (this.currentUserRole) {
            this.roleService.setCurrentUserRole(this.currentUserRole);
            this.userPermissions = this.roleService.getPermissionsForRole(this.currentUserRole);
            this.canCreateUsers = this.roleService.canCreateUsers(this.currentUserRole);
            this.canDeleteUsers = this.roleService.canDeleteUsers(this.currentUserRole);
            this.canManageRoles = this.roleService.canManageRoles(this.currentUserRole);
            
            this.assignableRoles = this.roleService.getAssignableRoles(this.currentUserRole);
            console.log('Assignable roles:', this.assignableRoles);
          }
        },
        error: (error) => {
          console.error('Error loading user profile:', error);
          this.fallbackPermissions();
        }
      });
  }

  /**
   * Méthode robuste pour extraire le rôle de l'utilisateur
   */
  private extractUserRole(user: any): UserRole | null {
    const userRoles = this.authService.getCurrentUserRoles();
    if (userRoles && userRoles.length > 0) {
      return userRoles[0];
    }
    return null;
  }

  /**
   * Fallback en cas d'erreur de chargement du profil
   */
  private fallbackPermissions(): void {
    this.currentUserRole = this.authService.getCurrentUserRole();
    
    if (this.currentUserRole) {
      this.canCreateUsers = this.roleService.canCreateUsers(this.currentUserRole);
      this.canDeleteUsers = this.roleService.canDeleteUsers(this.currentUserRole);
      this.canManageRoles = this.roleService.canManageRoles(this.currentUserRole);
    }
  }

  /**
   * Charge les rôles disponibles
   */
  private loadAvailableRoles(): void {
    this.hubUsersService.getAvailableHubRoles()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response) => {
          this.availableRoles = response.roles.map(role => ({
            value: role.value,
            label: role.label,
            description: role.description
          }));
          console.log('Available hub roles loaded:', this.availableRoles);
        },
        error: (error) => {
          console.error('Error loading available roles:', error);
          this.availableRoles = this.getFallbackRoles();
        }
      });
  }

  /**
   * Rôles par défaut en cas d'erreur
   */
  private getFallbackRoles(): any[] {
    return [
      { value: UserRole.DCB_ADMIN, label: 'DCB Admin', description: 'Administrateur système' },
      { value: UserRole.DCB_SUPPORT, label: 'DCB Support', description: 'Support technique' },
      { value: UserRole.DCB_PARTNER, label: 'DCB Partner', description: 'Partenaire commercial' }
    ];
  }

  private getDefaultUserForm() {
    return {
      username: '',
      email: '',
      firstName: '',
      lastName: '',
      password: '',
      role: UserRole.DCB_SUPPORT,
      enabled: true,
      emailVerified: false,
      userType: UserType.HUB
    };
  }

  // ==================== MÉTHODES D'INTERFACE ====================

  userProfiles: { [userId: string]: any } = {}; // Stocker les profils par userId
  users: any[] = []; // Liste des utilisateurs
  loadingProfiles: { [userId: string]: boolean } = {}; // État de chargement par user

  // Méthode pour changer d'onglet
  showTab(tab: 'list' | 'profile', userId?: string) {
    console.log(`Switching to tab: ${tab}`, userId ? `for user ${userId}` : '');
    this.activeTab = tab;
    
    if (userId) {
      this.selectedUserId = userId;
      // Charger le profil si pas déjà chargé
      if (!this.userProfiles[userId]) {
        this.loadUserProfile(userId);
      }
    } else {
      this.selectedUserId = null;
    }
  }

  // Charger un profil spécifique
  loadUserProfile(userId: string) {
    if (this.loadingProfiles[userId]) return; // Éviter les doublons
    
    this.loadingProfiles[userId] = true;
    
    this.hubUsersService.getHubUserById(userId).subscribe({
      next: (profile) => {
        this.userProfiles[userId] = profile;
        this.loadingProfiles[userId] = false;
        console.log(`Profile loaded for user ${userId}:`, profile);
      },
      error: (error) => {
        console.error(`Error loading profile for user ${userId}:`, error);
        this.loadingProfiles[userId] = false;
      }
    });
  }

  // Getter pour le profil actuel
  get currentProfile() {
    return this.selectedUserId ? this.userProfiles[this.selectedUserId] : null;
  }

  // Getter pour l'état de chargement
  get isLoadingProfile() {
    return this.selectedUserId ? this.loadingProfiles[this.selectedUserId] : false;
  }

  backToList() {
    console.log('🔙 Returning to list view');
    this.activeTab = 'list';
    this.selectedUserId = null;
  }

  // Méthodes de gestion des événements du composant enfant
  onUserSelected(userId: string) {
    this.showTab('profile', userId);
  }

  onResetPasswordRequested(event: any) {
    const userId = typeof event === 'string' ? event : event.detail || event;
    this.openResetPasswordModal(userId);
  }

  onDeleteUserRequested(event: any) {
    const userId = typeof event === 'string' ? event : event.detail || event;
    this.openDeleteUserModal(userId);
  }

  // ==================== GESTION DES MODALS ====================

  openModal(content: TemplateRef<any>, size: 'sm' | 'lg' | 'xl' = 'lg') {
    this.modalService.open(content, { 
      size: size,
      centered: true,
      scrollable: true 
    });
  }

  // Méthode pour ouvrir le modal de création d'utilisateur
  openCreateUserModal() {
    if (!this.canCreateUsers) {
      console.warn('User does not have permission to create users');
      return;
    }

    this.resetUserForm();
    this.createUserError = '';
    this.openModal(this.createUserModal);
  }

  private resetUserForm() {
    this.newUser = {
      username: '',
      email: '',
      firstName: '',
      lastName: '',
      password: '',
      role: UserRole.DCB_SUPPORT,
      enabled: true,
      emailVerified: false,
      userType: UserType.HUB
    };
    console.log('🔄 Hub user form reset');
  }

  // Méthode pour ouvrir le modal de réinitialisation de mot de passe
  openResetPasswordModal(userId: string) {
    this.hubUsersService.getHubUserById(userId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.selectedUserForReset = user;
          this.newPassword = '';
          this.temporaryPassword = false;
          this.resetPasswordError = '';
          this.resetPasswordSuccess = '';
          this.openModal(this.resetPasswordModal);
          console.log('✅ Hub user loaded for password reset:', user.username);
        },
        error: (error) => {
          console.error('❌ Error loading hub user for password reset:', error);
          this.resetPasswordError = 'Erreur lors du chargement de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  // Méthode pour ouvrir le modal de suppression
  openDeleteUserModal(userId: string) {
    if (!this.canDeleteUsers) {
      console.warn('User does not have permission to delete users');
      return;
    }

    console.log(`🗑️ Opening delete modal for hub user: ${userId}`);
    this.hubUsersService.getHubUserById(userId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.selectedUserForDelete = user;
          this.deleteUserError = '';
          this.openModal(this.deleteUserModal);
          console.log('✅ Hub user loaded for deletion:', user.username);
        },
        error: (error) => {
          console.error('❌ Error loading hub user for deletion:', error);
          this.deleteUserError = 'Erreur lors du chargement de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  onRoleSelectionChange(selectedRole: UserRole) {
    this.newUser.role = selectedRole;
  }

  // ==================== OPÉRATIONS CRUD ====================

  createUser() {
    if (!this.canCreateUsers) {
      this.createUserError = 'Vous n\'avez pas la permission de créer des utilisateurs';
      return;
    }

    const validation = this.validateUserForm();
    if (!validation.isValid) {
      this.createUserError = validation.error!;
      console.error('❌ Form validation failed:', validation.error);
      return;
    }

    // Vérifier la permission pour attribuer le rôle sélectionné
    if (!this.canAssignRole(this.newUser.role)) {
      this.createUserError = `Vous n'avez pas la permission d'attribuer le rôle: ${this.getRoleLabel(this.newUser.role)}`;
      return;
    }

    this.creatingUser = true;
    this.createUserError = '';

    console.log('📤 Creating hub user with data:', this.newUser);

    this.hubUsersService.createHubUser(this.newUser)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (createdUser) => {
          console.log('✅ Hub user created successfully:', createdUser);
          this.creatingUser = false;
          this.modalService.dismissAll();
          this.refreshUsersList();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('❌ Error creating hub user:', error);
          this.creatingUser = false;
          this.createUserError = this.getErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  /**
   * Vérifie si l'utilisateur peut attribuer un rôle spécifique
   */
  canAssignRole(targetRole: UserRole): boolean {
    return this.roleService.canAssignRole(this.currentUserRole, targetRole);
  }

  // Réinitialiser le mot de passe
  confirmResetPassword() {
    if (!this.selectedUserForReset || !this.newPassword || this.newPassword.length < 8) {
      this.resetPasswordError = 'Veuillez saisir un mot de passe valide (au moins 8 caractères).';
      console.error('❌ Password reset validation failed');
      return;
    }

    console.log('🔑 Confirming password reset for hub user:', this.selectedUserForReset.username);

    this.resettingPassword = true;
    this.resetPasswordError = '';
    this.resetPasswordSuccess = '';

    const resetPasswordDto: ResetPasswordDto = {
      newPassword: this.newPassword,
      temporary: this.temporaryPassword
    };

    this.hubUsersService.resetHubUserPassword(
      this.selectedUserForReset.id,
      resetPasswordDto 
    ).pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response) => {
          console.log('✅ Hub user password reset successfully');
          this.resettingPassword = false;
          this.resetPasswordSuccess = 'Mot de passe réinitialisé avec succès !';
          this.cdRef.detectChanges();
          
          // Fermer le modal après 2 secondes
          setTimeout(() => {
            this.modalService.dismissAll();
          }, 2000);
        },
        error: (error) => {
          console.error('❌ Error resetting hub user password:', error);
          this.resettingPassword = false;
          this.resetPasswordError = this.getResetPasswordErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  confirmDeleteUser() {
    if (!this.selectedUserForDelete || !this.canDeleteUsers) {
      console.error('❌ No hub user selected for deletion or no permission');
      return;
    }

    console.log('🗑️ Confirming hub user deletion:', this.selectedUserForDelete.username);

    this.deletingUser = true;
    this.deleteUserError = '';

    this.hubUsersService.deleteHubUser(this.selectedUserForDelete.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          console.log('✅ Hub user deleted successfully');
          this.deletingUser = false;
          this.modalService.dismissAll();
          this.refreshUsersList();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('❌ Error deleting hub user:', error);
          this.deletingUser = false;
          this.deleteUserError = this.getDeleteErrorMessage(error);
          this.cdRef.detectChanges();
        }
      });
  }

  // ==================== MÉTHODES UTILITAIRES ====================

  private refreshUsersList(): void {
    if (this.hubUsersList && typeof this.hubUsersList.refreshData === 'function') {
      console.log('🔄 Refreshing hub users list...');
      this.hubUsersList.refreshData();
    } else {
      console.warn('❌ HubUsersList component not available for refresh');
      this.showTab('list');
    }
  }

  // Méthodes proxy pour le template
  getRoleBadgeClass(role: UserRole): string {
    return this.roleService.getRoleBadgeClass(role);
  }

  getRoleLabel(role: UserRole): string {
    return this.roleService.getRoleLabel(role);
  }

  getRoleIcon(role: UserRole): string {
    return this.roleService.getRoleIcon(role);
  }

  getRoleDescription(role: UserRole): string {
    const roleInfo = this.availableRoles.find(r => r.value === role);
    return roleInfo?.description || 'Description non disponible';
  }

  getUserInitials(user: any): string {
    return (user.firstName?.charAt(0) || '') + (user.lastName?.charAt(0) || '') || 'U';
  }

  // ==================== GESTION DES ERREURS ====================

  private getErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 400) {
      return 'Données invalides. Vérifiez les champs du formulaire.';
    }
    if (error.status === 409) {
      return 'Un utilisateur avec ce nom d\'utilisateur ou email existe déjà.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions nécessaires pour cette action.';
    }
    return 'Erreur lors de la création de l\'utilisateur. Veuillez réessayer.';
  }

  private getResetPasswordErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 404) {
      return 'Utilisateur non trouvé.';
    }
    if (error.status === 400) {
      return 'Le mot de passe ne respecte pas les critères de sécurité.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions pour réinitialiser ce mot de passe.';
    }
    return 'Erreur lors de la réinitialisation du mot de passe. Veuillez réessayer.';
  }

  private getDeleteErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 404) {
      return 'Utilisateur non trouvé.';
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions pour supprimer cet utilisateur.';
    }
    if (error.status === 409) {
      return 'Impossible de supprimer cet utilisateur car il est associé à des données.';
    }
    return 'Erreur lors de la suppression de l\'utilisateur. Veuillez réessayer.';
  }

  // ==================== VALIDATION DU FORMULAIRE ====================

  private validateUserForm(): { isValid: boolean; error?: string } {
    const requiredFields = [
      { field: this.newUser.username?.trim(), name: 'Nom d\'utilisateur' },
      { field: this.newUser.email?.trim(), name: 'Email' },
      { field: this.newUser.firstName?.trim(), name: 'Prénom' },
      { field: this.newUser.lastName?.trim(), name: 'Nom' }
    ];

    for (const { field, name } of requiredFields) {
      if (!field) {
        return { isValid: false, error: `${name} est requis` };
      }
    }

    // Validation email
    const email = this.newUser.email?.trim();
    if (!email) {
      return { isValid: false, error: 'Email est requis' };
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return { isValid: false, error: 'Format d\'email invalide' };
    }

    if (!this.newUser.password || this.newUser.password.length < 8) {
      return { isValid: false, error: 'Le mot de passe doit contenir au moins 8 caractères' };
    }

    if (!this.newUser.role) {
      return { isValid: false, error: 'Le rôle est requis' };
    }

    return { isValid: true };
  }
}