import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { DcbDashboardData, KpiCardModel, PaymentChartData, SubscriptionStatsModel, Alert } from '../models/dcb-dashboard.models';
import { environment } from '@environments/environment';

@Injectable({ providedIn: 'root' })
export class DcbDashboardService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.localServiceTestApiUrl}/dcb-dashboard`;

  // Données mockées pour le développement
  private mockData: DcbDashboardData = {
    kpis: [
      {
        title: 'Revenue Total',
        value: 125430,
        change: 12.5,
        changeType: 'positive',
        icon: 'lucideTrendingUp',
        color: 'success',
        format: 'currency',
        currency: 'XOF'
      },
      {
        title: 'Paiements Today',
        value: 342,
        change: -2.3,
        changeType: 'negative',
        icon: 'lucideCreditCard',
        color: 'primary',
        format: 'number'
      },
      {
        title: 'Taux de Succès',
        value: 98.2,
        change: 1.2,
        changeType: 'positive',
        icon: 'lucideCheckCircle',
        color: 'info',
        format: 'percentage'
      },
      {
        title: 'Abonnements Actifs',
        value: 12543,
        change: 8.7,
        changeType: 'positive',
        icon: 'lucideUsers',
        color: 'warning',
        format: 'number'
      }
    ],
    paymentChart: [
      { period: 'Jan', successful: 12000, failed: 300, pending: 500, revenue: 4500000 },
      { period: 'Fév', successful: 15000, failed: 250, pending: 400, revenue: 5200000 },
      { period: 'Mar', successful: 18000, failed: 200, pending: 300, revenue: 6100000 },
      { period: 'Avr', successful: 22000, failed: 150, pending: 250, revenue: 7500000 },
      { period: 'Mai', successful: 25000, failed: 100, pending: 200, revenue: 8900000 },
      { period: 'Jun', successful: 30000, failed: 80, pending: 150, revenue: 10500000 }
    ],
    subscriptionStats: {
      total: 15600,
      active: 12543,
      trial: 1850,
      cancelled: 857,
      expired: 350,
      growthRate: 8.7
    },
    alerts: [
      {
        id: '1',
        type: 'warning',
        title: 'Taux d\'échec élevé Orange CI',
        message: 'Le taux d\'échec des paiements Orange Côte d\'Ivoire a augmenté de 15%',
        timestamp: new Date(Date.now() - 30 * 60 * 1000), // 30 minutes ago
        acknowledged: false,
        priority: 'medium',
        action: {
          label: 'Voir les détails',
          route: '/payments'
        }
      },
      {
        id: '2',
        type: 'info',
        title: 'Maintenance planifiée',
        message: 'Maintenance système prévue ce soir de 22h à 00h',
        timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2 hours ago
        acknowledged: false,
        priority: 'low'
      },
      {
        id: '3',
        type: 'success',
        title: 'Nouveau partenaire activé',
        message: 'Le partenaire "MTN Senegal" a été configuré avec succès',
        timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000), // 4 hours ago
        acknowledged: true,
        priority: 'low'
      }
    ],
    lastUpdated: new Date()
  };

  getDcbDashboardData(): Observable<DcbDashboardData> {
    // En production, utiliser l'API réelle
    if (environment.production) {
      return this.http.get<DcbDashboardData>(this.apiUrl).pipe(
        catchError(() => of(this.mockData)) // Fallback sur les données mockées en cas d'erreur
      );
    }
    
    // En développement, retourner les données mockées
    return of(this.mockData);
  }

  acknowledgeAlert(alertId: string): Observable<{ success: boolean }> {
    // Simuler l'acknowledgement
    const alert = this.mockData.alerts.find(a => a.id === alertId);
    if (alert) {
      alert.acknowledged = true;
    }
    
    return of({ success: true });
  }

  refreshData(): Observable<DcbDashboardData> {
    // Simuler un rafraîchissement des données
    this.mockData.lastUpdated = new Date();
    return of(this.mockData);
  }
}