import { Component, inject, OnInit, TemplateRef, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon } from '@ng-icons/core';
import { NgbAlertModule, NgbModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { UsersService } from '@modules/users/services/users.service';
import { AuthService } from '@core/services/auth.service';
import { UserResponse, UpdateUserDto } from '@modules/users/models/user';

@Component({
  selector: 'app-my-profile',
  standalone: true,
  imports: [CommonModule, FormsModule, NgIcon, NgbAlertModule, NgbModalModule],
  templateUrl: './profile.html',
  styles: [`
    .avatar-lg {
      width: 80px;
      height: 80px;
    }
    .fs-24 {
      font-size: 24px;
    }
  `]
})
export class MyProfile implements OnInit {
  private usersService = inject(UsersService);
  private authService = inject(AuthService);
  private modalService = inject(NgbModal);
  private cdRef = inject(ChangeDetectorRef);

  @ViewChild('resetPasswordModal') resetPasswordModal!: TemplateRef<any>;

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

  // Édition
  isEditing = false;
  editedUser: UpdateUserDto = {};

  // Réinitialisation mot de passe
  newPassword = '';
  temporaryPassword = false;
  resettingPassword = false;
  resetPasswordError = '';
  resetPasswordSuccess = '';

  ngOnInit() {
    this.loadMyProfile();
  }

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

    this.usersService.getCurrentUserProfile().subscribe({
      next: (user) => {
        this.user = user;
        this.loading = false;
        this.cdRef.detectChanges(); 
      },
      error: (error) => {
        this.error = 'Erreur lors du chargement de votre profil';
        this.loading = false;
        this.cdRef.detectChanges(); 
        console.error('Error loading my profile:', error);
      }
    });
  }

  // Ouvrir le modal de réinitialisation de mot de passe
  openResetPasswordModal() {
    if (!this.user) return;
    
    this.newPassword = '';
    this.temporaryPassword = false;
    this.resetPasswordError = '';
    this.resetPasswordSuccess = '';

    this.modalService.open(this.resetPasswordModal, { 
      centered: true,
      size: 'md'
    });
  }

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

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

    const resetDto = {
      userId: this.user.id,
      newPassword: this.newPassword,
      temporary: this.temporaryPassword
    };

    this.usersService.resetPassword(resetDto).subscribe({
      next: () => {
        this.resettingPassword = false;
        this.resetPasswordSuccess = 'Votre mot de passe a été réinitialisé avec succès !';
        this.cdRef.detectChanges();
        
        // Déconnexion automatique si mot de passe temporaire
        if (this.temporaryPassword) {
          setTimeout(() => {
            this.authService.logout();
          }, 2000);
        }
      },
      error: (error) => {
        this.resettingPassword = false;
        this.resetPasswordError = this.getResetPasswordErrorMessage(error);
        this.cdRef.detectChanges();
        console.error('Error resetting password:', error);
      }
    });
  }

  // Gestion des erreurs pour la réinitialisation
  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é.';
    }
    return 'Erreur lors de la réinitialisation du mot de passe. Veuillez réessayer.';
  }

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

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

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

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

    this.usersService.updateCurrentUserProfile(this.editedUser).subscribe({
      next: (updatedUser) => {
        this.user = updatedUser;
        this.isEditing = false;
        this.saving = false;
        this.success = 'Profil mis à jour avec succès';
        this.editedUser = {};
      },
      error: (error) => {
        this.error = 'Erreur lors de la mise à jour du profil';
        this.saving = false;
        console.error('Error updating profile:', 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';
    }
  }
}