import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { BilletsService } from '../../services/billets.service';

/**
 * Composant de liste des PNR
 */
@Component({
  selector: 'app-pnr-list',
  templateUrl: './pnr-list.component.html',
  styleUrls: ['./pnr-list.component.scss'],
  providers: [BilletsService]
})
export class PnrListComponent implements OnInit, OnDestroy {
  
  private destroy$ = new Subject<void>();
  
  pnrList: any[] = [];
  selectedItems: any[] = [];
  loading = false;
  
  // Badges/KPIs
  badges: any[] = [
    { title: 'Total PNR', icon: 'flight_takeoff', result: 0 },
    { title: 'Passagers', icon: 'people', result: 0 },
    { title: 'Confirmés', icon: 'check_circle', result: 0 },
    { title: 'En Attente', icon: 'schedule', result: 0 }
  ];
  
  // CTAs
  ctas: any[] = [
    { action: 'create', label: 'Nouveau PNR', icon: 'add' },
    { action: 'import', label: 'Importer', icon: 'upload' },
    { action: 'export', label: 'Exporter', icon: 'file_download' },
    { action: 'refresh', label: 'Actualiser', icon: 'refresh' }
  ];

  constructor(private billetsService: BilletsService) {}

  ngOnInit(): void {
    this.loadData();
  }

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

  /**
   * Charge les données
   */
  loadData(): void {
    this.loading = true;
    
    this.billetsService.getPnr().pipe(
      takeUntil(this.destroy$)
    ).subscribe({
      next: (data) => {
        this.pnrList = data;
        this.calculateBadges();
        this.loading = false;
      },
      error: (error) => {
        console.error('Erreur lors du chargement:', error);
        this.loading = false;
      }
    });
  }

  /**
   * Calcule les badges/KPIs
   */
  private calculateBadges(): void {
    this.badges = [
      {
        title: 'Total PNR',
        icon: 'flight_takeoff',
        result: this.pnrList.length
      },
      {
        title: 'Passagers',
        icon: 'people',
        result: this.pnrList.reduce((sum, item) => sum + (item.passenger_count || 0), 0)
      },
      {
        title: 'Confirmés',
        icon: 'check_circle',
        result: this.pnrList.filter(item => item.status === 'confirmed').length
      },
      {
        title: 'En Attente',
        icon: 'schedule',
        result: this.pnrList.filter(item => item.status === 'pending').length
      }
    ];
  }

  /**
   * Gestion des actions
   */
  onActionTriggered(action: string): void {
    switch (action) {
      case 'create':
        this.createPnr();
        break;
      case 'import':
        this.importData();
        break;
      case 'export':
        this.exportData();
        break;
      case 'refresh':
        this.refreshData();
        break;
      default:
        console.log('Action non gérée:', action);
    }
  }

  /**
   * Actions
   */
  private createPnr(): void {
    console.log('Créer un nouveau PNR');
    // TODO: Ouvrir le formulaire de création
  }

  private importData(): void {
    console.log('Importer des PNR');
    // TODO: Implémenter l'import
  }

  private exportData(): void {
    console.log('Exporter les données');
    // TODO: Implémenter l'export
  }

  private refreshData(): void {
    this.billetsService.refreshData();
    this.loadData();
  }

  /**
   * Gestion de la sélection des lignes
   */
  onRowsSelected(selectedRows: any[]): void {
    this.selectedItems = selectedRows;
  }

  /**
   * Gestion du double-clic sur une ligne
   */
  onRowDoubleClicked(item: any): void {
    console.log('Détail du PNR:', item);
    // TODO: Ouvrir la vue détail
  }

  /**
   * Retourne la couleur selon le statut
   */
  getStatusColor(status: string): string {
    switch (status) {
      case 'confirmed': return '#28a745';
      case 'pending': return '#ffc107';
      case 'cancelled': return '#dc3545';
      default: return '#6c757d';
    }
  }

  /**
   * Retourne le libellé du statut
   */
  getStatusLabel(status: string): string {
    switch (status) {
      case 'confirmed': return 'Confirmé';
      case 'pending': return 'En attente';
      case 'cancelled': return 'Annulé';
      default: return status;
    }
  }

  /**
   * TrackBy function pour optimiser le rendu
   */
  trackByFn(index: number, item: any): any {
    return item.id || index;
  }

  /**
   * Toggle la sélection d'un élément
   */
  toggleSelection(item: any): void {
    const index = this.selectedItems.findIndex(selected => selected.id === item.id);
    if (index > -1) {
      this.selectedItems.splice(index, 1);
    } else {
      this.selectedItems.push(item);
    }
  }

  /**
   * Gestion du changement de sélection globale
   */
  onSelectAllChange(event: Event): void {
    const target = event.target as HTMLInputElement;
    if (target.checked) {
      this.onRowsSelected(this.pnrList);
    } else {
      this.onRowsSelected([]);
    }
  }
}
