import { Component, inject, OnInit, Input, Output, EventEmitter, ChangeDetectorRef } 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 { UsersService } from '../services/users.service';
import { UserResponse, UpdateUserDto, ClientRole } from '../models/user';

@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 {
  private usersService = inject(UsersService);
  private cdRef = inject(ChangeDetectorRef);

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

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

  // Édition
  isEditing = false;
  editedUser: UpdateUserDto = {};
  
  // Gestion des rôles
  availableRoles: ClientRole[] = ['admin', 'merchant', 'support', 'user'];
  selectedRoles: ClientRole[] = [];
  updatingRoles = false;

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

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

    this.usersService.getUserById(this.userId).subscribe({
      next: (user) => {
        this.user = user;
        this.selectedRoles = user.clientRoles
          .filter((role): role is ClientRole => 
            this.availableRoles.includes(role as ClientRole)
          );
        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() {
    this.isEditing = true;
    this.editedUser = {
      firstName: this.user?.firstName,
      lastName: this.user?.lastName,
      email: this.user?.email,
      username: this.user?.username,
      enabled: this.user?.enabled,
      emailVerified: this.user?.emailVerified
    };
    this.cdRef.detectChanges(); 
  }

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

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

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

    this.usersService.updateUser(this.user.id, this.editedUser).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 = 'Erreur lors de la mise à jour du profil';
        this.saving = false;
        this.cdRef.detectChanges(); 
        console.error('Error updating user:', error);
      }
    });
  }

  // Gestion des rôles
  toggleRole(role: ClientRole) {
    const index = this.selectedRoles.indexOf(role);
    if (index > -1) {
      this.selectedRoles.splice(index, 1);
    } else {
      this.selectedRoles.push(role);
    }
    this.cdRef.detectChanges(); 
  }

  isRoleSelected(role: ClientRole): boolean {
    return this.selectedRoles.includes(role);
  }

  updateUserRoles() {
    if (!this.user) return;

    this.updatingRoles = true;
    this.usersService.assignClientRoles(this.user.id, this.selectedRoles).subscribe({
      next: () => {
        this.updatingRoles = false;
        this.success = 'Rôles mis à jour avec succès';
        if (this.user) {
          this.user.clientRoles = [...this.selectedRoles];
        }
        this.cdRef.detectChanges(); 
      },
      error: (error) => {
        this.updatingRoles = false;
        this.error = 'Erreur lors de la mise à jour des rôles';
        this.cdRef.detectChanges(); 
        console.error('Error updating roles:', error);
      }
    });
  }

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

    this.usersService.enableUser(this.user.id).subscribe({
      next: () => {
        this.user!.enabled = true;
        this.success = 'Utilisateur activé avec succès';
        this.cdRef.detectChanges(); 
      },
      error: (error) => {
        this.error = 'Erreur lors de l\'activation de l\'utilisateur';
        this.cdRef.detectChanges(); 
        console.error('Error enabling user:', error);
      }
    });
  }

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

    this.usersService.disableUser(this.user.id).subscribe({
      next: () => {
        this.user!.enabled = false;
        this.success = 'Utilisateur désactivé avec succès';
        this.cdRef.detectChanges(); 
      },
      error: (error) => {
        this.error = 'Erreur lors de la désactivation de l\'utilisateur';
        this.cdRef.detectChanges(); 
        console.error('Error disabling user:', error);
      }
    });
  }

  // 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 {
    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: string): string {
    switch (role) {
      case 'admin': return 'bg-danger';
      case 'merchant': return 'bg-success';
      case 'support': return 'bg-info';
      case 'user': return 'bg-secondary';
      default: return 'bg-secondary';
    }
  }
}