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 états de ventes
 */
@Component({
  selector: 'app-etatsdeventes-list',
  templateUrl: './etatsdeventes-list.component.html',
  styleUrls: ['./etatsdeventes-list.component.scss'],
  providers: [BilletsService]
})
export class EtatsdeventesListComponent implements OnInit, OnDestroy {
  
  private destroy$ = new Subject<void>();
  
  etatsdeventes: any[] = [];
  selectedItems: any[] = [];
  loading = false;
  
  // Badges/KPIs
  badges: any[] = [
    { title: 'Total Billets', icon: 'airplane_ticket', result: 0 },
    { title: 'Chiffre d\'Affaires', icon: 'euro', result: 0 },
    { title: 'Commissions', icon: 'percent', result: 0 },
    { title: 'Billets du Jour', icon: 'today', result: 0 }
  ];
  
  // CTAs
  ctas: any[] = [
    { action: 'create', label: 'Nouveau Billet', icon: 'add' },
    { 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.getEtatsdeventes().pipe(
      takeUntil(this.destroy$)
    ).subscribe({
      next: (data) => {
        this.etatsdeventes = 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 {
    const today = new Date().toDateString();
    
    this.badges = [
      {
        title: 'Total Billets',
        icon: 'airplane_ticket',
        result: this.etatsdeventes.length
      },
      {
        title: 'Chiffre d\'Affaires',
        icon: 'euro',
        result: this.etatsdeventes.reduce((sum, item) => sum + (item.amount || 0), 0)
      },
      {
        title: 'Commissions',
        icon: 'percent',
        result: this.etatsdeventes.reduce((sum, item) => sum + (item.commission || 0), 0)
      },
      {
        title: 'Billets du Jour',
        icon: 'today',
        result: this.etatsdeventes.filter(item => 
          new Date(item.created_at).toDateString() === today
        ).length
      }
    ];
  }

  /**
   * 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 de l\'état de vente:', item);
    // TODO: Ouvrir la vue détail
  }

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

  /**
   * Actions
   */
  private createEtatdevente(): void {
    console.log('Créer un nouvel état de vente');
    // TODO: Ouvrir le formulaire de création
  }

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

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

  /**
   * Retourne la couleur selon le statut
   */
  getStatusColor(status: string): string {
    switch (status) {
      case 'issued': 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 'issued': return 'Émis';
      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;
  }

  /**
   * TrackBy function appelée trackByEtat dans le template
   */
  trackByEtat(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);
    }
  }

  /**
   * Sélection d'un item (appelée par le template)
   */
  onItemSelect(item: any, event: Event): void {
    this.toggleSelection(item);
  }

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

  /**
   * Actions du menu contextuel
   */
  viewEtat(item: any): void {
    console.log('Voir détail:', item);
    this.onRowDoubleClicked(item);
  }

  editEtat(item: any): void {
    console.log('Modifier:', item);
  }

  downloadTicket(item: any): void {
    console.log('Télécharger billet:', item);
  }

  deleteEtat(item: any): void {
    console.log('Supprimer:', item);
  }
}
