// src/app/modules/merchant-users/list/list.ts
import { Component, inject, OnInit, Output, EventEmitter, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbPaginationModule, NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap';
import { catchError, map, of, Subject, takeUntil } from 'rxjs';
import { 
  MerchantUsersService, 
  MerchantUserResponse, 
  UserRole,
} from '../services/merchant-partners.service';

import { HubUsersService, UserRole as HubUserRole } from '../../users/services/users.service';

import { AuthService } from '@core/services/auth.service';
import { UiCard } from '@app/components/ui-card';

@Component({
  selector: 'app-merchant-users-list',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    UiCard, 
    NgbPaginationModule,
    NgbDropdownModule
  ],
  templateUrl: './list.html',
})
export class MerchantUsersList implements OnInit, OnDestroy {
  private merchantUsersService = inject(MerchantUsersService);
  private hubUsersService = inject(HubUsersService);
  private authService = inject(AuthService);
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();

  readonly UserRole = UserRole;
  readonly HubUserRole = HubUserRole;

  @Output() userSelected = new EventEmitter<string>();
  @Output() openCreateModal = new EventEmitter<void>();
  @Output() openResetPasswordModal = new EventEmitter<string>();
  @Output() openDeleteUserModal = new EventEmitter<string>();

  // Données
  allUsers: MerchantUserResponse[] = [];
  filteredUsers: MerchantUserResponse[] = [];
  displayedUsers: MerchantUserResponse[] = [];
  
  // États
  loading = false;
  error = '';

  // Recherche et filtres
  searchTerm = '';
  statusFilter: 'all' | 'enabled' | 'disabled' = 'all';
  emailVerifiedFilter: 'all' | 'verified' | 'not-verified' = 'all';
  roleFilter: UserRole | 'all' = 'all';

  // Pagination
  currentPage = 1;
  itemsPerPage = 10;
  totalItems = 0;
  totalPages = 0;

  // Tri
  sortField: keyof MerchantUserResponse = 'username';
  sortDirection: 'asc' | 'desc' = 'asc';

  // Rôles disponibles pour le filtre
  availableRoles: { value: UserRole | 'all'; label: string }[] = [
    { value: 'all', label: 'Tous les rôles' },
    { value: UserRole.DCB_PARTNER_ADMIN, label: 'Administrateurs' },
    { value: UserRole.DCB_PARTNER_MANAGER, label: 'Managers' },
    { value: UserRole.DCB_PARTNER_SUPPORT, label: 'Support' }
  ];

  // ID du merchant partner courant et permissions
  currentMerchantPartnerId: string = '';
  currentUserRole: HubUserRole | null = null;
  isHubAdminOrSupport = false;
  canViewAllMerchants = false;
  isDcbPartner = false;

  ngOnInit() {
    this.loadCurrentUserPermissions();
  }

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

  private loadCurrentUserPermissions() {
    this.authService.getProfile().subscribe({
      next: (user: any) => {
        // Méthode robuste pour récupérer le rôle
        this.currentUserRole = this.extractUserRole(user);
        
        // Déterminer le type d'utilisateur
        this.isHubAdminOrSupport = this.currentUserRole === HubUserRole.DCB_ADMIN || 
                                  this.currentUserRole === HubUserRole.DCB_SUPPORT;
        this.isDcbPartner = this.currentUserRole === HubUserRole.DCB_PARTNER;
        this.canViewAllMerchants = this.isHubAdminOrSupport;

        // Déterminer le merchantPartnerId
        this.currentMerchantPartnerId = this.extractMerchantPartnerId(user);

        console.log('🎯 Final Permissions:', {
          currentUserRole: this.currentUserRole,
          isHubAdminOrSupport: this.isHubAdminOrSupport,
          isDcbPartner: this.isDcbPartner,
          canViewAllMerchants: this.canViewAllMerchants,
          currentMerchantPartnerId: this.currentMerchantPartnerId
        });

        this.loadUsers();
      },
      error: (error) => {
        console.error('❌ Error loading current user permissions:', error);
        this.loadUsers(); // Charger quand même les utilisateurs
      }
    });
  }

  /**
   * Extrait le rôle de l'utilisateur de manière robuste
   */
  private extractUserRole(user: any): HubUserRole | null {
    // Essayer différentes sources possibles pour le rôle
    if (user.roles && user.roles.length > 0) {
      return user.roles[0] as HubUserRole;
    }
    
    if (user.role) {
      return user.role as HubUserRole;
    }
        
    console.warn('No role found in user profile');
    return null;
  }

  /**
   * Extrait le merchantPartnerId de manière robuste
   */
  private extractMerchantPartnerId(user: any): string {
    if (this.isDcbPartner) {
      // Pour DCB_PARTNER, utiliser son ID comme merchantPartnerId
      return user.id || '';
    }
    
    // Pour les autres, chercher le merchantPartnerId dans différentes sources
    if (user.merchantPartnerId) {
      return user.merchantPartnerId;
    }
    
    if (user.attributes?.merchantPartnerId?.[0]) {
      return user.attributes.merchantPartnerId[0];
    }
    
    if (user.attributes?.partnerId?.[0]) {
      return user.attributes.partnerId[0];
    }
    
    console.warn('No merchantPartnerId found in user profile');
    return '';
  }

  loadUsers() {
    this.loading = true;
    this.error = '';

    console.log('🚀 Loading users with permissions:', {
      canViewAllMerchants: this.canViewAllMerchants,
      currentMerchantPartnerId: this.currentMerchantPartnerId,
      currentUserRole: this.currentUserRole
    });

    let usersObservable;

    if (this.canViewAllMerchants) {
      // Admin/Support DCB : charger tous les utilisateurs via HubUsersService
      console.log('📊 Loading ALL merchant users (DCB Admin view)');
      
      usersObservable = this.hubUsersService.findAllMerchantUsers(1, 1000).pipe(
        map((response: any) => {
          console.log('📦 Hub Users API Response:', response);
          
          // Adapter selon la structure de votre API
          if (response && response.users) {
            return response.users;
          } else if (Array.isArray(response)) {
            return response;
          }
          return [];
        }),
        catchError(error => {
          console.error('❌ Error loading hub users:', error);
          return of([]);
        })
      );
    } else if (this.currentMerchantPartnerId) {
      // Utilisateur marchand (DCB_PARTNER) : charger seulement ses utilisateurs
      console.log('🏢 Loading merchant users for partner:', this.currentMerchantPartnerId);
      
      usersObservable = this.merchantUsersService.getMyMerchantUsers().pipe(
        catchError(error => {
          console.error('❌ Error loading merchant users:', error);
          return of([]);
        })
      );
    } else {
      this.error = 'Impossible de déterminer les permissions de chargement';
      this.loading = false;
      console.error('❌ No valid permission scenario');
      return;
    }

    usersObservable
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (users: any[]) => {
          this.allUsers = users || [];
          
          this.applyFiltersAndPagination();
          this.loading = false;
          this.cdRef.detectChanges(); 
        },
        error: (error: any) => {
          this.error = 'Erreur lors du chargement des utilisateurs marchands';
          this.loading = false;
          
          this.allUsers = [];
          this.filteredUsers = [];
          this.displayedUsers = [];
          this.cdRef.detectChanges();
          console.error('❌ Error in users subscription:', error);
        }
      });
  }

  // Recherche et filtres
  onSearch() {
    this.currentPage = 1;
    this.applyFiltersAndPagination();
  }

  onClearFilters() {
    this.searchTerm = '';
    this.statusFilter = 'all';
    this.emailVerifiedFilter = 'all';
    this.roleFilter = 'all';
    this.currentPage = 1;
    this.applyFiltersAndPagination();
  }

  applyFiltersAndPagination() {
    // Vérifier que allUsers est défini
    if (!this.allUsers) {
      this.allUsers = [];
    }

    // Appliquer les filtres
    this.filteredUsers = this.allUsers.filter(user => {
      // Filtre de recherche
      const matchesSearch = !this.searchTerm || 
        user.username.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        user.email.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        (user.firstName && user.firstName.toLowerCase().includes(this.searchTerm.toLowerCase())) ||
        (user.lastName && user.lastName.toLowerCase().includes(this.searchTerm.toLowerCase()));

      // Filtre par statut
      const matchesStatus = this.statusFilter === 'all' || 
        (this.statusFilter === 'enabled' && user.enabled) ||
        (this.statusFilter === 'disabled' && !user.enabled);

      // Filtre par email vérifié
      const matchesEmailVerified = this.emailVerifiedFilter === 'all' ||
        (this.emailVerifiedFilter === 'verified' && user.emailVerified) ||
        (this.emailVerifiedFilter === 'not-verified' && !user.emailVerified);

      // Filtre par rôle
      const matchesRole = this.roleFilter === 'all' || user.role === this.roleFilter;

      return matchesSearch && matchesStatus && matchesEmailVerified && matchesRole;
    });

    // Appliquer le tri
    this.filteredUsers.sort((a, b) => {
      const aValue = a[this.sortField];
      const bValue = b[this.sortField];
      
      if (aValue === bValue) return 0;
      
      let comparison = 0;
      if (typeof aValue === 'string' && typeof bValue === 'string') {
        comparison = aValue.localeCompare(bValue);
      } else if (typeof aValue === 'number' && typeof bValue === 'number') {
        comparison = aValue - bValue;
      } else if (typeof aValue === 'boolean' && typeof bValue === 'boolean') {
        comparison = (aValue === bValue) ? 0 : aValue ? -1 : 1;
      }
      
      return this.sortDirection === 'asc' ? comparison : -comparison;
    });

    // Calculer la pagination
    this.totalItems = this.filteredUsers.length;
    this.totalPages = Math.ceil(this.totalItems / this.itemsPerPage);
    
    // Appliquer la pagination
    const startIndex = (this.currentPage - 1) * this.itemsPerPage;
    const endIndex = startIndex + this.itemsPerPage;
    this.displayedUsers = this.filteredUsers.slice(startIndex, endIndex);
  }

  // Tri
  sort(field: keyof MerchantUserResponse) {
    if (this.sortField === field) {
      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortField = field;
      this.sortDirection = 'asc';
    }
    this.applyFiltersAndPagination();
  }

  getSortIcon(field: keyof MerchantUserResponse): string {
    if (this.sortField !== field) return 'lucideArrowUpDown';
    return this.sortDirection === 'asc' ? 'lucideArrowUp' : 'lucideArrowDown';
  }

  // Pagination
  onPageChange(page: number) {
    this.currentPage = page;
    this.applyFiltersAndPagination();
  }

  getStartIndex(): number {
    return (this.currentPage - 1) * this.itemsPerPage + 1;
  }

  getEndIndex(): number {
    return Math.min(this.currentPage * this.itemsPerPage, this.totalItems);
  }

  // Actions
  viewUserProfile(userId: string) {
    this.userSelected.emit(userId);
  }

  // Méthode pour réinitialiser le mot de passe
  resetPassword(user: MerchantUserResponse) {
    this.openResetPasswordModal.emit(user.id);
  }

  // Méthode pour ouvrir le modal de suppression
  deleteUser(user: MerchantUserResponse) {
    this.openDeleteUserModal.emit(user.id);
  }

  // Activer un utilisateur
  enableUser(user: MerchantUserResponse) {
    this.merchantUsersService.enableMerchantUser(user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          user.enabled = updatedUser.enabled;
          this.applyFiltersAndPagination();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('Error enabling merchant user:', error);
          this.error = 'Erreur lors de l\'activation de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  // Désactiver un utilisateur
  disableUser(user: MerchantUserResponse) {
    this.merchantUsersService.disableMerchantUser(user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          user.enabled = updatedUser.enabled;
          this.applyFiltersAndPagination();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('Error disabling merchant user:', error);
          this.error = 'Erreur lors de la désactivation de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  // ==================== UTILITAIRES D'AFFICHAGE ====================

  getStatusBadgeClass(user: MerchantUserResponse): string {
    if (!user.enabled) return 'badge bg-danger';
    if (!user.emailVerified) return 'badge bg-warning';
    return 'badge bg-success';
  }

  getStatusText(user: MerchantUserResponse): string {
    if (!user.enabled) return 'Désactivé';
    if (!user.emailVerified) return 'Email non vérifié';
    return 'Actif';
  }

  getRoleBadgeClass(role: UserRole): string {
    switch (role) {
      case UserRole.DCB_PARTNER_ADMIN:
        return 'bg-danger';
      case UserRole.DCB_PARTNER_MANAGER:
        return 'bg-warning text-dark';
      case UserRole.DCB_PARTNER_SUPPORT:
        return 'bg-info text-white';
      default:
        return 'bg-secondary';
    }
  }

  getRoleDisplayName(role: UserRole): string {
    const roleNames = {
      [UserRole.DCB_PARTNER_ADMIN]: 'Administrateur',
      [UserRole.DCB_PARTNER_MANAGER]: 'Manager',
      [UserRole.DCB_PARTNER_SUPPORT]: 'Support'
    };
    return roleNames[role] || role;
  }

  getRoleIcon(role: UserRole): string {
    switch (role) {
      case UserRole.DCB_PARTNER_ADMIN:
        return 'lucideShield';
      case UserRole.DCB_PARTNER_MANAGER:
        return 'lucideUserCog';
      case UserRole.DCB_PARTNER_SUPPORT:
        return 'lucideHeadphones';
      default:
        return 'lucideUser';
    }
  }

  formatTimestamp(timestamp: number): string {
    if (!timestamp) return 'Non disponible';
    return new Date(timestamp).toLocaleDateString('fr-FR', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

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

  getUserDisplayName(user: MerchantUserResponse): string {
    if (user.firstName && user.lastName) {
      return `${user.firstName} ${user.lastName}`;
    }
    return user.username;
  }

  // ==================== STATISTIQUES ====================

  getUsersCountByRole(role: UserRole): number {
    return this.allUsers.filter(user => user.role === role).length;
  }

  getEnabledUsersCount(): number {
    return this.allUsers.filter(user => user.enabled).length;
  }

  getDisabledUsersCount(): number {
    return this.allUsers.filter(user => !user.enabled).length;
  }

  getEmailVerifiedCount(): number {
    return this.allUsers.filter(user => user.emailVerified).length;
  }

  getTotalUsersCount(): number {
    return this.allUsers.length;
  }

  // ==================== VÉRIFICATIONS DE PERMISSIONS ====================

  canManageUser(user: MerchantUserResponse): boolean {
    // Logique pour déterminer si l'utilisateur connecté peut gérer cet utilisateur
    // À adapter selon votre logique métier
    return true;
  }

  canDeleteUser(user: MerchantUserResponse): boolean {
    // Empêcher la suppression de soi-même
    // À adapter avec l'ID de l'utilisateur connecté
    return user.id !== 'current-user-id';
  }

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

  hasRole(user: MerchantUserResponse, role: UserRole): boolean {
    return user.role === role;
  }

  isAdmin(user: MerchantUserResponse): boolean {
    return this.hasRole(user, UserRole.DCB_PARTNER_ADMIN);
  }

  isManager(user: MerchantUserResponse): boolean {
    return this.hasRole(user, UserRole.DCB_PARTNER_MANAGER);
  }

  isSupport(user: MerchantUserResponse): boolean {
    return this.hasRole(user, UserRole.DCB_PARTNER_SUPPORT);
  }

  // Recherche rapide par rôle
  filterByRole(role: UserRole | 'all') {
    this.roleFilter = role;
    this.currentPage = 1;
    this.applyFiltersAndPagination();
  }

  // Recherche via le service (pour des recherches plus complexes)
  searchUsers() {
    if (this.searchTerm.trim()) {
      this.loading = true;
      this.merchantUsersService.searchMerchantUsers({ 
        query: this.searchTerm,
        role: this.roleFilter !== 'all' ? this.roleFilter as UserRole : undefined,
        enabled: this.statusFilter !== 'all' ? this.statusFilter === 'enabled' : undefined
      })
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (users) => {
          this.allUsers = users;
          this.applyFiltersAndPagination();
          this.loading = false;
          this.cdRef.detectChanges();
        },
        error: (error: any) => {
          console.error('Error searching users:', error);
          this.loading = false;
          this.cdRef.detectChanges();
        }
      });
    } else {
      this.loadUsers(); // Recharger tous les utilisateurs si la recherche est vide
    }
  }
}