import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { AuthenticationService } from '../../../core/services/authentication.service';

@Component({
  selector: 'app-modern-header',
  templateUrl: './modern-header.component.html',
  styleUrls: ['./modern-header.component.scss']
})
export class ModernHeaderComponent implements OnInit {

  @Output() menuToggle = new EventEmitter<void>();
  @Output() searchQuery = new EventEmitter<string>();

  public currentUser: any = null;
  public breadcrumb: any[] = [];
  public notificationCount = 3;
  public searchValue = '';
  public showUserMenu = false;

  constructor(
    private router: Router,
    private dialog: MatDialog,
    private authService: AuthenticationService
  ) {}

  ngOnInit(): void {
    this.initializeUser();
    this.initializeBreadcrumb();
  }

  private initializeUser(): void {
    const userData = localStorage.getItem('__user');
    if (userData) {
      try {
        const user = JSON.parse(userData);
        this.currentUser = {
          name: user.fullname || user.firstname || 'Utilisateur',
          email: user.email || '',
          avatar: this.generateAvatar(user.fullname || user.firstname || 'U'),
          role: user.role || 'Utilisateur'
        };
      } catch (error) {
        this.currentUser = {
          name: 'Utilisateur',
          email: '',
          avatar: 'U',
          role: 'Utilisateur'
        };
      }
    }
  }

  private initializeBreadcrumb(): void {
    const url = this.router.url;
    const segments = url.split('/').filter(segment => segment);
    
    this.breadcrumb = [];
    
    if (segments.length >= 2) {
      const domain = segments[1];
      this.breadcrumb.push({
        label: this.formatLabel(domain),
        icon: this.getDomainIcon(domain),
        route: `/admin/${domain}`,
        active: false
      });
      
      if (segments.length >= 3) {
        const module = segments[2];
        this.breadcrumb.push({
          label: this.formatLabel(module),
          icon: this.getModuleIcon(module),
          route: `/admin/${domain}/${module}/list`,
          active: true
        });
      }
    }
  }

  private generateAvatar(name: string): string {
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .substring(0, 2);
  }

  private formatLabel(text: string): string {
    return text.charAt(0).toUpperCase() + text.slice(1);
  }

  private getDomainIcon(domain: string): string {
    const icons: { [key: string]: string } = {
      'customers': 'people',
      'billets': 'airplane_ticket',
      'finance': 'account_balance',
      'support': 'support_agent'
    };
    return icons[domain.toLowerCase()] || 'folder';
  }

  private getModuleIcon(module: string): string {
    const icons: { [key: string]: string } = {
      'accounts': 'account_circle',
      'contacts': 'contacts',
      'etatsdeventes': 'receipt',
      'pnr': 'flight_takeoff'
    };
    return icons[module.toLowerCase()] || 'list';
  }

  onMenuToggle(): void {
    this.menuToggle.emit();
  }

  onSearchChange(value: string): void {
    this.searchValue = value;
    this.searchQuery.emit(value);
  }

  toggleUserMenu(): void {
    this.showUserMenu = !this.showUserMenu;
  }

  onLogout(): void {
    console.log('🔒 ModernHeader: Déconnexion demandée');

    // Utiliser AuthenticationService au lieu de localStorage.clear()
    // pour éviter le crash causé par l'effacement de toutes les données
    this.authService.logout().subscribe({
      next: () => {
        console.log('✅ ModernHeader: Déconnexion réussie');
        this.router.navigate(['/login']);
      },
      error: (error) => {
        console.error('❌ ModernHeader: Erreur lors de la déconnexion:', error);
        // En cas d'erreur, forcer la déconnexion quand même
        localStorage.clear();
        this.router.navigate(['/login']);
      }
    });
  }

  /**
   * Ouvrir le panneau FAQ
   */
  toggleFaqPanel(): void {
    console.log('Opening FAQ panel...');

    // Vérifier si les composants FAQ existent
    try {
      // Import dynamique du composant FAQ
      import('../../../components/faq/faq.component').then(m => {
        const dialogRef = this.dialog.open(m.FaqComponent, {
          id: 'faq-panel',
          position: { right: '0' },
          panelClass: ['animate__animated', 'animate__slideInRight', 'full-h-pop'],
          maxWidth: '450px',
          height: '100vh'
        });

        dialogRef.afterClosed().subscribe(() => {
          console.log('FAQ panel closed');
        });
      }).catch(error => {
        console.error('Error loading FAQ component:', error);
        // Fallback: naviguer vers une page FAQ simple ou afficher un message
        alert('Centre d\'aide temporairement indisponible. Contactez le support technique.');
      });
    } catch (error) {
      console.error('Error opening FAQ:', error);
      // Fallback simple
      alert('Centre d\'aide : FAQ sera bientôt disponible !');
    }
  }

  /**
   * Afficher le profil utilisateur
   */
  showUserProfile(): void {
    console.log('Opening user profile...');
    this.showUserMenu = false; // Fermer le dropdown

    try {
      // Récupérer les données complètes depuis localStorage
      const userData = localStorage.getItem('__user');
      let userDataToPass = {};

      if (userData) {
        try {
          const parsedData = JSON.parse(userData);
          userDataToPass = parsedData;
          console.log('Passing user data to profile:', userDataToPass);
        } catch (error) {
          console.error('Error parsing user data for profile:', error);
          userDataToPass = this.currentUser;
        }
      } else {
        userDataToPass = this.currentUser;
      }

      // Import dynamique du composant Profil
      import('../../../components/profil/profil.component').then(m => {
        const dialogRef = this.dialog.open(m.ProfilComponent, {
          id: 'profil-panel',
          data: userDataToPass,
          position: { right: '0', top: '0' },
          panelClass: ['animate__animated', 'animate__slideInRight', 'full-h-pop'],
          maxWidth: '400px',
          height: '100vh'
        });

        dialogRef.afterClosed().subscribe(() => {
          console.log('Profile panel closed');
        });
      }).catch(error => {
        console.error('Error loading Profile component:', error);
        // Fallback: afficher les informations utilisateur de base
        alert(`Profil utilisateur:\nNom: ${this.currentUser?.name}\nEmail: ${this.currentUser?.email}`);
      });
    } catch (error) {
      console.error('Error opening Profile:', error);
      // Fallback simple
      const userInfo = `Utilisateur: ${this.currentUser?.name || 'Inconnu'}\nRôle: ${this.currentUser?.role || 'Non défini'}`;
      alert(userInfo);
    }
  }
}