import { Component, inject, OnInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideNgIconsConfig } from '@ng-icons/core';
import { 
  lucideSearch,
  lucideFilter,
  lucideX,
  lucideDownload,
  lucideEye,
  lucideRefreshCw,
  lucideArrowUpDown,
  lucideArrowUp,
  lucideArrowDown,
  lucideCheckCircle,
  lucideClock,
  lucideXCircle,
  lucideUndo2,
  lucideBan
} from '@ng-icons/lucide';
import { NgbPaginationModule, NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';

import { TransactionsService } from '../services/transactions.service';
import { Transaction, TransactionQuery, TransactionStatus, PaginatedTransactions } from '../models/transaction';
import { environment } from '@environments/environment';

@Component({
  selector: 'app-transactions-list',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon,
    NgbPaginationModule,
    NgbDropdownModule,
    NgbTooltipModule
  ],
  providers: [
    provideNgIconsConfig({
      size: '1.25em'
    })
  ],
  templateUrl: './list.html'
})
export class TransactionsList implements OnInit {
  private transactionsService = inject(TransactionsService);
  private cdRef = inject(ChangeDetectorRef);

  @Output() transactionSelected = new EventEmitter<string>();
  @Output() openRefundModal = new EventEmitter<string>();

  // Données
  transactions: Transaction[] = [];
  paginatedData: PaginatedTransactions | null = null;
  
  // États
  loading = false;
  error = '';
  
  // Filtres et recherche
  searchTerm = '';
  filters: TransactionQuery = {
    page: 1,
    limit: 20,
    status: undefined,
    operator: '',
    country: '',
    startDate: undefined,
    endDate: undefined,
    msisdn: '',
    sortBy: 'transactionDate',
    sortOrder: 'desc'
  };

  // Options de filtre
  statusOptions: TransactionStatus[] = ['PENDING', 'SUCCESS', 'FAILED', 'REFUNDED', 'CANCELLED'];
  operatorOptions: string[] = ['Orange', 'Free', 'SFR', 'Bouygues'];
  countryOptions: string[] = ['FR', 'BE', 'CH', 'LU'];
  
  // Tri
  sortField: string = 'transactionDate';
  sortDirection: 'asc' | 'desc' = 'desc';

  // Sélection multiple
  selectedTransactions: Set<string> = new Set();
  selectAll = false;

  ngOnInit() {
    this.loadTransactions();
  }

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

    // Mettre à jour les filtres avec la recherche
    if (this.searchTerm) {
      this.filters.search = this.searchTerm;
    } else {
      delete this.filters.search;
    }

    // Appliquer le tri
    this.filters.sortBy = this.sortField;
    this.filters.sortOrder = this.sortDirection;

    this.transactionsService.getTransactions(this.filters).subscribe({
      next: (data) => {
        this.paginatedData = data;
        this.transactions = data.data;
        this.loading = false;
        this.cdRef.detectChanges();
      },
      error: (error) => {
        this.error = 'Erreur lors du chargement des transactions';
        this.loading = false;
        
        // Fallback sur les données mockées en développement
        if (environment.production === false) {
          this.transactions = this.transactionsService.getMockTransactions();
          this.paginatedData = {
            data: this.transactions,
            total: this.transactions.length,
            page: 1,
            limit: 20,
            totalPages: 1,
            stats: {
              total: this.transactions.length,
              totalAmount: this.transactions.reduce((sum, tx) => sum + tx.amount, 0),
              successCount: this.transactions.filter(tx => tx.status === 'SUCCESS').length,
              failedCount: this.transactions.filter(tx => tx.status === 'FAILED').length,
              pendingCount: this.transactions.filter(tx => tx.status === 'PENDING').length,
              refundedCount: this.transactions.filter(tx => tx.status === 'REFUNDED').length,
              successRate: 75,
              averageAmount: 4.74
            }
          };
          this.loading = false;
        }
        
        this.cdRef.detectChanges();
        console.error('Error loading transactions:', error);
      }
    });
  }

  // Recherche et filtres
  onSearch() {
    this.filters.page = 1;
    this.loadTransactions();
  }

  onClearFilters() {
    this.searchTerm = '';
    this.filters = {
      page: 1,
      limit: 20,
      status: undefined,
      operator: '',
      country: '',
      startDate: undefined,
      endDate: undefined,
      msisdn: '',
      sortBy: 'transactionDate',
      sortOrder: 'desc'
    };
    this.loadTransactions();
  }

  onStatusFilterChange(status: TransactionStatus | 'all') {
    this.filters.status = status === 'all' ? undefined : status;
    this.filters.page = 1;
    this.loadTransactions();
  }

  onOperatorFilterChange(operator: string) {
    this.filters.operator = operator;
    this.filters.page = 1;
    this.loadTransactions();
  }

  onDateRangeChange(start: Date | null, end: Date | null) {
    this.filters.startDate = start || undefined;
    this.filters.endDate = end || undefined;
    this.filters.page = 1;
    this.loadTransactions();
  }

  // Tri
  sort(field: string) {
    if (this.sortField === field) {
      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortField = field;
      this.sortDirection = 'desc';
    }
    this.loadTransactions();
  }

  getSortIcon(field: string): string {
    if (this.sortField !== field) return 'lucideArrowUpDown';
    return this.sortDirection === 'asc' ? 'lucideArrowUp' : 'lucideArrowDown';
  }

  // Pagination
  onPageChange(page: number) {
    this.filters.page = page;
    this.loadTransactions();
  }

  // Actions
  viewTransactionDetails(transactionId: string) {
    this.transactionSelected.emit(transactionId);
  }

  refundTransaction(transactionId: string) {
    this.openRefundModal.emit(transactionId);
  }

  retryTransaction(transactionId: string) {
    this.transactionsService.retryTransaction(transactionId).subscribe({
      next: () => {
        this.loadTransactions();
      },
      error: (error) => {
        console.error('Error retrying transaction:', error);
        this.error = 'Erreur lors de la nouvelle tentative';
        this.cdRef.detectChanges();
      }
    });
  }

  // Sélection multiple
  toggleTransactionSelection(transactionId: string) {
    if (this.selectedTransactions.has(transactionId)) {
      this.selectedTransactions.delete(transactionId);
    } else {
      this.selectedTransactions.add(transactionId);
    }
    this.updateSelectAllState();
  }

  toggleSelectAll() {
    if (this.selectAll) {
      this.transactions.forEach(tx => this.selectedTransactions.add(tx.id));
    } else {
      this.selectedTransactions.clear();
    }
  }

  updateSelectAllState() {
    this.selectAll = this.transactions.length > 0 && 
                    this.selectedTransactions.size === this.transactions.length;
  }

  // Export
  exportTransactions(format: 'csv' | 'excel' | 'pdf') {
    const exportRequest = {
      format: format,
      query: this.filters,
      columns: ['id', 'msisdn', 'operator', 'amount', 'status', 'transactionDate', 'productName']
    };

    this.transactionsService.exportTransactions(exportRequest).subscribe({
      next: (response) => {
        // Télécharger le fichier
        const link = document.createElement('a');
        link.href = response.url;
        link.download = response.filename;
        link.click();
      },
      error: (error) => {
        console.error('Error exporting transactions:', error);
        this.error = 'Erreur lors de l\'export';
        this.cdRef.detectChanges();
      }
    });
  }

  // Utilitaires d'affichage
  getStatusBadgeClass(status: TransactionStatus): string {
    switch (status) {
      case 'SUCCESS': return 'badge bg-success';
      case 'PENDING': return 'badge bg-warning';
      case 'FAILED': return 'badge bg-danger';
      case 'REFUNDED': return 'badge bg-info';
      case 'CANCELLED': return 'badge bg-secondary';
      case 'EXPIRED': return 'badge bg-dark';
      default: return 'badge bg-secondary';
    }
  }

  getStatusIcon(status: TransactionStatus): string {
    switch (status) {
      case 'SUCCESS': return 'lucideCheckCircle';
      case 'PENDING': return 'lucideClock';
      case 'FAILED': return 'lucideXCircle';
      case 'REFUNDED': return 'lucideUndo2';
      case 'CANCELLED': return 'lucideBan';
      default: return 'lucideClock';
    }
  }

  formatCurrency(amount: number, currency: string = 'EUR'): string {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: currency
    }).format(amount);
  }

  formatDate(date: Date): string {
    return new Intl.DateTimeFormat('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    }).format(new Date(date));
  }

  getAmountColor(amount: number): string {
    if (amount >= 10) return 'text-danger fw-bold';
    if (amount >= 5) return 'text-warning fw-semibold';
    return 'text-success';
  }

  // Méthodes pour sécuriser l'accès aux stats
  getTotal(): number {
    return this.paginatedData?.stats?.total || 0;
  }

  getSuccessCount(): number {
    return this.paginatedData?.stats?.successCount || 0;
  }

  getFailedCount(): number {
    return this.paginatedData?.stats?.failedCount || 0;
  }

  getPendingCount(): number {
    return this.paginatedData?.stats?.pendingCount || 0;
  }

  getSuccessRate(): number {
    return this.paginatedData?.stats?.successRate || 0;
  }

  getTotalAmount(): number {
    return this.paginatedData?.stats?.totalAmount || 0;
  }

  getMinValue(a: number, b: number): number {
    return Math.min(a, b);
  }
}