import { Component, inject, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideNgIconsConfig } from '@ng-icons/core';

import { PageTitle } from '@app/components/page-title/page-title';

import { 
  lucideEuro, 
  lucideCreditCard, 
  lucideBarChart3, 
  lucideSmartphone,
  lucideTrendingUp,
  lucideTrendingDown,
  lucideAlertCircle,
  lucideCheckCircle,
  lucideClock,
  lucideXCircle,
  lucideRefreshCw
} from '@ng-icons/lucide';
import { NgbAlertModule, NgbProgressbarModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';

import { DcbService } from './services/dcb.service';
import { DcbAnalytics, TransactionStats, DcbTransaction, DcbOperator } from './models/dcb';

// Type pour les plages de temps
type TimeRange = '24h' | '7d' | '30d' | '90d';

@Component({
  selector: 'app-dcb-dashboard',
  standalone: true,
  imports: [
    CommonModule, 
    FormsModule, 
    NgIcon, 
    NgbAlertModule, 
    NgbProgressbarModule,
    NgbTooltipModule,
    PageTitle
  ],
  providers: [
    provideNgIconsConfig({
      size: '1.25em'
    })
  ],
  templateUrl: './dcb-dashboard.html'
})
export class DcbDashboard implements OnInit, OnDestroy {
  private dcbService = inject(DcbService);
  private cdRef = inject(ChangeDetectorRef);

  // États
  loading = false;
  error = '';
  lastUpdated: Date | null = null;
  
  // Données
  analytics: DcbAnalytics | null = null;
  stats: TransactionStats | null = null;
  recentTransactions: DcbTransaction[] = [];
  operators: DcbOperator[] = [];

  // Filtres
  timeRange: TimeRange = '7d';
  autoRefresh = true;
  private refreshInterval: any;

  // Plages de temps disponibles (pour le template)
  timeRanges: TimeRange[] = ['24h', '7d', '30d', '90d'];

  ngOnInit() {
    this.loadDashboardData();
    this.startAutoRefresh();
  }

  ngOnDestroy() {
    this.stopAutoRefresh();
  }

  startAutoRefresh() {
    if (this.autoRefresh) {
      this.refreshInterval = setInterval(() => {
        this.loadDashboardData();
      }, 30000); // Refresh toutes les 30 secondes
    }
  }

  stopAutoRefresh() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  }

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

    // Charger toutes les données en parallèle
    Promise.all([
      this.dcbService.getAnalytics(this.timeRange).toPromise(),
      this.dcbService.getTransactionStats().toPromise(),
      this.dcbService.getRecentTransactions(8).toPromise(),
      this.dcbService.getOperators().toPromise()
    ]).then(([analytics, stats, transactions, operators]) => {
      this.analytics = analytics || null;
      this.stats = stats || null;
      this.recentTransactions = transactions || [];
      this.operators = operators || [];
      this.loading = false;
      this.lastUpdated = new Date();
      this.cdRef.detectChanges();
    }).catch(error => {
      this.error = 'Erreur lors du chargement des données du dashboard';
      this.loading = false;
      this.lastUpdated = new Date();
      this.cdRef.detectChanges();
      console.error('Dashboard loading error:', error);
    });
  }

  onTimeRangeChange(range: TimeRange) {
    this.timeRange = range;
    this.loadDashboardData();
  }

  onRefresh() {
    this.loadDashboardData();
  }

  onAutoRefreshToggle() {
    this.autoRefresh = !this.autoRefresh;
    if (this.autoRefresh) {
      this.startAutoRefresh();
    } else {
      this.stopAutoRefresh();
    }
  }

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

  formatNumber(num: number): string {
    return new Intl.NumberFormat('fr-FR').format(num);
  }

  formatPercentage(value: number): string {
    return `${value.toFixed(1)}%`;
  }

  getStatusBadgeClass(status: string): 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';
      default: return 'badge bg-secondary';
    }
  }

  getStatusIcon(status: string): string {
    switch (status) {
      case 'SUCCESS': return 'lucideCheckCircle';
      case 'PENDING': return 'lucideClock';
      case 'FAILED': return 'lucideXCircle';
      case 'REFUNDED': return 'lucideRefreshCw';
      default: return 'lucideAlertCircle';
    }
  }

  getGrowthClass(growth: number): string {
    return growth >= 0 ? 'text-success' : 'text-danger';
  }

  getGrowthIcon(growth: number): string {
    return growth >= 0 ? 'lucideTrendingUp' : 'lucideTrendingDown';
  }

  getOperatorStatusClass(status: string): string {
    return status === 'ACTIVE' ? 'badge bg-success' : 'badge bg-secondary';
  }

  getSuccessRateClass(rate: number): string {
    if (rate >= 90) return 'text-success';
    if (rate >= 80) return 'text-warning';
    return 'text-danger';
  }

  getProgressBarClass(rate: number): string {
    if (rate >= 90) return 'bg-success';
    if (rate >= 80) return 'bg-warning';
    return 'bg-danger';
  }
}