// src/app/modules/users/list/list.ts
import { Component, inject, OnInit, Output, EventEmitter, ChangeDetectorRef, Input, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbPaginationModule } from '@ng-bootstrap/ng-bootstrap';
import { Subject, takeUntil } from 'rxjs';
import { HubUsersService, HubUserResponse, UserRole } from '../services/users.service';
import { RoleManagementService } from '@core/services/role-management.service';
import { UiCard } from '@app/components/ui-card';

@Component({
  selector: 'app-users-list',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    UiCard, 
    NgbPaginationModule
  ],
  templateUrl: './list.html',
})
export class UsersList implements OnInit, OnDestroy {
  private usersService = inject(HubUsersService);
  private roleService = inject(RoleManagementService);
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();
  
  readonly UserRole = UserRole;

  @Input() canCreateUsers: boolean = false;
  @Input() canDeleteUsers: boolean = false;

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

  // Données
  allUsers: HubUserResponse[] = [];
  filteredUsers: HubUserResponse[] = [];
  displayedUsers: HubUserResponse[] = [];
  
  // É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 HubUserResponse = 'username';
  sortDirection: 'asc' | 'desc' = 'asc';

  // Rôles disponibles pour le filtre
  availableRoles = [
    { value: 'all' as const, label: 'Tous les rôles' },
    { value: UserRole.DCB_ADMIN, label: 'Administrateurs' },
    { value: UserRole.DCB_SUPPORT, label: 'Support' },
    { value: UserRole.DCB_PARTNER, label: 'Partenaires' }
  ];

  ngOnInit() {
    this.loadUsers();
  }

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

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

    this.usersService.findAllUsers()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response) => {
          this.allUsers = response.users;
          this.applyFiltersAndPagination();
          this.loading = false;
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.error = 'Erreur lors du chargement des utilisateurs';
          this.loading = false;
          this.cdRef.detectChanges();
          console.error('Error loading users:', 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() {
    // 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?.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        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 HubUserResponse) {
    if (this.sortField === field) {
      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortField = field;
      this.sortDirection = 'asc';
    }
    this.applyFiltersAndPagination();
  }

  getSortIcon(field: keyof HubUserResponse): 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: HubUserResponse) {
    this.openResetPasswordModal.emit(user.id);
  }

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

  enableUser(user: HubUserResponse) {
    this.usersService.enableUser(user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          user.enabled = true;
          this.applyFiltersAndPagination();
          this.cdRef.detectChanges();
        },
        error: (error) => {
          console.error('Error enabling user:', error);
          this.error = 'Erreur lors de l\'activation de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  disableUser(user: HubUserResponse) {
    this.usersService.disableUser(user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          user.enabled = false;
          this.applyFiltersAndPagination();
          this.cdRef.detectChanges();
        },
        error: (error) =>{
          console.error('Error disabling user:', error);
          this.error = 'Erreur lors de la désactivation de l\'utilisateur';
          this.cdRef.detectChanges();
        }
      });
  }

  // Utilitaires d'affichage
  getStatusBadgeClass(user: HubUserResponse): string {
    if (!user.enabled) return 'badge bg-danger';
    if (!user.emailVerified) return 'badge bg-warning';
    return 'badge bg-success';
  }

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

  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);
  }

  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: HubUserResponse): string {
    return (user.firstName?.charAt(0) || '') + (user.lastName?.charAt(0) || '') || 'U';
  }

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

  // Statistiques
  /**
 * Récupère le nombre d'utilisateurs par rôle (méthode publique pour le template)
 */
  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;
  }

  // Vérification des permissions pour les actions
  canManageUser(user: HubUserResponse): boolean {
    // Implémentez votre logique de permission ici
    // Par exemple, empêcher un utilisateur de se modifier lui-même
    return true;
  }

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