import { Component, inject, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
import { userDropdownItems } from '@layouts/components/data';
import { AuthService } from '@/app/core/services/auth.service';
import { User, UserRole } from '@core/models/dcb-bo-hub-user.model';
import { Subject, takeUntil } from 'rxjs';

@Component({
  selector: 'app-user-profile',
  standalone: true,
  imports: [NgbCollapseModule],
  templateUrl: './user-profile.component.html',
})
export class UserProfileComponent implements OnInit, OnDestroy {
  private authService = inject(AuthService);
  private cdr = inject(ChangeDetectorRef);
  
  private destroy$ = new Subject<void>();
  
  user: User | null = null;
  isLoading = true;

  ngOnInit(): void {
    this.loadUser();
    
    // Subscribe to auth state changes
    this.authService.getAuthState()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (isAuthenticated) => {
          if (isAuthenticated) {
            this.loadUser();
          } else {
            this.user = null;
            this.isLoading = false;
          }
        }
      });
  }

  loadUser(): void {
    this.isLoading = true;
    
    this.authService.getProfile()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (profile) => {
          this.user = profile;
          this.isLoading = false;
        },
        error: (error) => {
          console.error('Failed to load user profile:', error);
          this.user = null;
          this.isLoading = false;
        }
      });
  }

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

  // Helper methods for template
  getUserInitials(): string {
    if (!this.user?.firstName || !this.user?.lastName) {
      return 'UU'; // User Unknown
    }
    return `${this.user.firstName.charAt(0)}${this.user.lastName.charAt(0)}`.toUpperCase();
  }

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

  // Get user role with proper mapping
  getUserRole(user: User | null): string {
    if (!user) return 'Utilisateur';
    
    // Use role from profile or fallback to token roles
    const role = user.role || this.authService.getCurrentUserRoles();
    
    // Map role to display name
    const roleDisplayNames: { [key in UserRole]: string } = {
      [UserRole.DCB_ADMIN]: 'Administrateur',
      [UserRole.DCB_SUPPORT]: 'Support Technique',
      [UserRole.DCB_PARTNER]: 'Partenaire',
      [UserRole.DCB_PARTNER_ADMIN]: 'Admin Partenaire',
      [UserRole.DCB_PARTNER_MANAGER]: 'Manager Partenaire',
      [UserRole.DCB_PARTNER_SUPPORT]: 'Support Partenaire',
    };
    
    const primaryRole = role;
    return roleDisplayNames[primaryRole] || 'Utilisateur';
  }
}