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

@Component({
  selector: 'app-user-profile',
  standalone: true,
  imports: [CommonModule, FormsModule, NgIcon, NgbAlertModule],
  templateUrl: './profile.html',
  styles: [`
    .avatar-lg {
      width: 80px;
      height: 80px;
    }
    .fs-24 {
      font-size: 24px;
    }
  `]
})
export class UserProfile implements OnInit, OnDestroy {
  private usersService = inject(HubUsersService);
  private roleService = inject(RoleManagementService);
  private authService = inject(AuthService);
  private cdRef = inject(ChangeDetectorRef);
  private destroy$ = new Subject<void>();

  @Input() userId!: string;
  @Output() back = new EventEmitter<void>();
  @Output() openResetPasswordModal = new EventEmitter<string>();

  user: HubUserResponse | null = null;
  loading = false;
  saving = false;
  error = '';
  success = '';

  // Gestion des permissions
  currentUserRole: UserRole | null = null;
  canEditUsers = false;
  canManageRoles = false;
  canDeleteUsers = false;

  // Édition
  isEditing = false;
  editedUser: UpdateHubUserDto = {};
  
  // Gestion des rôles
  availableRoles: { value: UserRole; label: string; description: string }[] = [];
  updatingRoles = false;

  ngOnInit() {
    if (this.userId) {
      this.initializeUserPermissions();
      this.loadAvailableRoles();
      this.loadUserProfile();
    }
  }

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

  /**
   * Initialise les permissions de l'utilisateur courant
   */
  private initializeUserPermissions(): void {
    this.authService.loadUserProfile()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (profile) => {
          this.currentUserRole = profile?.roles?.[0] as UserRole || null;
          if (this.currentUserRole) {
            this.canEditUsers = this.roleService.canEditUsers(this.currentUserRole);
            this.canManageRoles = this.roleService.canManageRoles(this.currentUserRole);
            this.canDeleteUsers = this.roleService.canDeleteUsers(this.currentUserRole);
          }
        },
        error: (error) => {
          console.error('Error loading user permissions:', error);
        }
      });
  }

  /**
   * Charge les rôles disponibles
   */
  private loadAvailableRoles(): void {
    this.roleService.getAvailableRolesSimple()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (roles) => {
          this.availableRoles = roles;
        },
        error: (error) => {
          console.error('Error loading available roles:', error);
          // Fallback
          this.availableRoles = [
            { 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' }
          ];
        }
      });
  }

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

    this.usersService.getUserById(this.userId)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (user) => {
          this.user = user;
          this.loading = false;
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.error = 'Erreur lors du chargement du profil utilisateur';
          this.loading = false;
          this.cdRef.detectChanges(); 
          console.error('Error loading user profile:', error);
        }
      });
  }

  startEditing() {
    if (!this.canEditUsers) {
      this.error = 'Vous n\'avez pas la permission de modifier les utilisateurs';
      return;
    }

    this.isEditing = true;
    this.editedUser = {
      firstName: this.user?.firstName,
      lastName: this.user?.lastName,
      email: this.user?.email,
      enabled: this.user?.enabled
    };
    this.cdRef.detectChanges(); 
  }

  cancelEditing() {
    this.isEditing = false;
    this.editedUser = {};
    this.error = '';
    this.success = '';
    this.cdRef.detectChanges(); 
  }

  saveProfile() {
    if (!this.user || !this.canEditUsers) return;

    this.saving = true;
    this.error = '';
    this.success = '';

    this.usersService.updateUser(this.user.id, this.editedUser)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          this.user = updatedUser;
          this.isEditing = false;
          this.saving = false;
          this.success = 'Profil mis à jour avec succès';
          this.editedUser = {};
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.error = this.getErrorMessage(error);
          this.saving = false;
          this.cdRef.detectChanges(); 
        }
      });
  }

  // Gestion des rôles
  updateUserRole(newRole: UserRole) {
    if (!this.user || !this.canManageRoles) return;

    // Vérifier que l'utilisateur peut attribuer ce rôle
    if (!this.roleService.canAssignRole(this.currentUserRole, newRole)) {
      this.error = 'Vous n\'avez pas la permission d\'attribuer ce rôle';
      return;
    }

    this.updatingRoles = true;
    this.error = '';
    this.success = '';

    this.usersService.updateUserRole(this.user.id, newRole)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          this.user = updatedUser;
          this.updatingRoles = false;
          this.success = 'Rôle mis à jour avec succès';
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.updatingRoles = false;
          this.error = this.getErrorMessage(error);
          this.cdRef.detectChanges(); 
        }
      });
  }

  // Gestion du statut
  enableUser() {
    if (!this.user || !this.canEditUsers) return;

    this.usersService.enableUser(this.user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          this.user = updatedUser;
          this.success = 'Utilisateur activé avec succès';
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.error = this.getErrorMessage(error);
          this.cdRef.detectChanges(); 
        }
      });
  }

  disableUser() {
    if (!this.user || !this.canEditUsers) return;

    this.usersService.disableUser(this.user.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (updatedUser) => {
          this.user = updatedUser;
          this.success = 'Utilisateur désactivé avec succès';
          this.cdRef.detectChanges(); 
        },
        error: (error) => {
          this.error = this.getErrorMessage(error);
          this.cdRef.detectChanges(); 
        }
      });
  }

  // Réinitialisation du mot de passe
  resetPassword() {
    if (this.user) {
      this.openResetPasswordModal.emit(this.user.id);
    }
  }

  // Gestion des erreurs
  private getErrorMessage(error: any): string {
    if (error.error?.message) {
      return error.error.message;
    }
    if (error.status === 403) {
      return 'Vous n\'avez pas les permissions nécessaires pour cette action';
    }
    if (error.status === 404) {
      return 'Utilisateur non trouvé';
    }
    if (error.status === 400) {
      return 'Données invalides';
    }
    return 'Une erreur est survenue. Veuillez réessayer.';
  }

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

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

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

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

  getUserDisplayName(): string {
    if (!this.user) return 'Utilisateur';
    if (this.user.firstName && this.user.lastName) {
      return `${this.user.firstName} ${this.user.lastName}`;
    }
    return this.user.username;
  }

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

  // Vérification des permissions pour les actions
  canAssignRole(targetRole: UserRole): boolean {
    return this.roleService.canAssignRole(this.currentUserRole, targetRole);
  }

  // Vérifie si c'est le profil de l'utilisateur courant
  isCurrentUserProfile(): boolean {
    // Implémentez cette logique selon votre système d'authentification
    return false;
  }
}