import { Component, inject, OnInit, Input, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { NgIcon, provideNgIconsConfig } from '@ng-icons/core';
import { 
  lucideArrowLeft,
  lucideCopy,
  lucideRefreshCw,
  lucideDownload,
  lucidePrinter,
  lucideCheckCircle,
  lucideClock,
  lucideXCircle,
  lucideUndo2,
  lucideBan,
  lucideCalendar,
  lucideSmartphone,
  lucideEuro,
  lucidePackage,
  lucideUser,
  lucideGlobe,
  lucideAlertCircle,
  lucideInfo
} from '@ng-icons/lucide';
import { NgbAlertModule, NgbTooltipModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { TransactionsService } from '../services/transactions.service';
import { Transaction, TransactionStatus, RefundRequest } from '../models/transaction';

@Component({
  selector: 'app-transaction-details',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    RouterModule,
    NgIcon,
    NgbAlertModule,
    NgbTooltipModule
  ],
  providers: [
    provideNgIconsConfig({
      size: '1.25em'
    })
  ],
  templateUrl: './details.html'
})
export class TransactionDetails implements OnInit {
  private transactionsService = inject(TransactionsService);
  private modalService = inject(NgbModal);
  private cdRef = inject(ChangeDetectorRef);

  @Input() transactionId!: string;

  // Données
  transaction: Transaction | null = null;
  loading = false;
  error = '';
  success = '';

  // Actions
  refunding = false;
  retrying = false;

  ngOnInit() {
    if (this.transactionId) {
      this.loadTransactionDetails();
    }
  }

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

    this.transactionsService.getTransactionById(this.transactionId).subscribe({
      next: (transaction) => {
        this.transaction = transaction;
        this.loading = false;
        this.cdRef.detectChanges();
      },
      error: (error) => {
        this.error = 'Erreur lors du chargement des détails de la transaction';
        this.loading = false;
        
        // Données mockées pour le développement
        const mockTransactions = this.transactionsService.getMockTransactions();
        this.transaction = mockTransactions.find(tx => tx.id === this.transactionId) || mockTransactions[0];
        this.loading = false;
        
        this.cdRef.detectChanges();
        console.error('Error loading transaction details:', error);
      }
    });
  }

  // Actions sur la transaction
  refundTransaction() {
    if (!this.transaction) return;

    this.refunding = true;
    const refundRequest: RefundRequest = {
      transactionId: this.transaction.id,
      reason: 'Remboursement manuel par l\'administrateur'
    };

    this.transactionsService.refundTransaction(refundRequest).subscribe({
      next: (response) => {
        this.transaction = response.transaction;
        this.refunding = false;
        this.success = 'Transaction remboursée avec succès';
        this.cdRef.detectChanges();
      },
      error: (error) => {
        this.refunding = false;
        this.error = 'Erreur lors du remboursement de la transaction';
        this.cdRef.detectChanges();
        console.error('Error refunding transaction:', error);
      }
    });
  }

  retryTransaction() {
    if (!this.transaction) return;

    this.retrying = true;
    this.transactionsService.retryTransaction(this.transaction.id).subscribe({
      next: (response) => {
        this.transaction = response.transaction;
        this.retrying = false;
        this.success = 'Nouvelle tentative lancée avec succès';
        this.cdRef.detectChanges();
      },
      error: (error) => {
        this.retrying = false;
        this.error = 'Erreur lors de la nouvelle tentative';
        this.cdRef.detectChanges();
        console.error('Error retrying transaction:', error);
      }
    });
  }

  cancelTransaction() {
    if (!this.transaction) return;

    this.transactionsService.cancelTransaction(this.transaction.id).subscribe({
      next: () => {
        this.success = 'Transaction annulée avec succès';
        this.loadTransactionDetails(); // Recharger les données
        this.cdRef.detectChanges();
      },
      error: (error) => {
        this.error = 'Erreur lors de l\'annulation de la transaction';
        this.cdRef.detectChanges();
        console.error('Error cancelling transaction:', error);
      }
    });
  }

  // Utilitaires
  copyToClipboard(text: string) {
    navigator.clipboard.writeText(text).then(() => {
      this.success = 'Copié dans le presse-papier';
      setTimeout(() => this.success = '', 3000);
      this.cdRef.detectChanges();
    });
  }

  printDetails() {
    window.print();
  }

  // Méthode pour obtenir les clés des données personnalisées
  getCustomDataKeys(): string[] {
    if (!this.transaction?.customData) {
      return [];
    }
    return Object.keys(this.transaction.customData);
  }

  // Getters pour l'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';
    }
  }

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

  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',
      second: '2-digit'
    }).format(new Date(date));
  }

  formatRelativeTime(date: Date): string {
    const now = new Date();
    const diffMs = now.getTime() - new Date(date).getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 1) return 'À l\'instant';
    if (diffMins < 60) return `Il y a ${diffMins} min`;
    if (diffHours < 24) return `Il y a ${diffHours} h`;
    if (diffDays < 7) return `Il y a ${diffDays} j`;
    return this.formatDate(date);
  }

  canRefund(): boolean {
    return this.transaction?.status === 'SUCCESS';
  }

  canRetry(): boolean {
    return this.transaction?.status === 'FAILED';
  }

  canCancel(): boolean {
    return this.transaction?.status === 'PENDING';
  }

  showErrorDetails(): boolean {
    return !!this.transaction?.errorCode || !!this.transaction?.errorMessage;
  }
}