import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { map, delay } from 'rxjs/operators';

import {
  RoutesPerformanceDashboard,
  RouteStatusMetrics,
  VehicleMetrics,
  DriverMetrics,
  TransportModalMetrics,
  OperationalMetrics,
  VolumeMetrics,
  DashboardFilters,
  TimePeriod
} from '../interfaces/routes-performance.interface';

/**
 * 🎯 RoutesPerformanceService
 * 
 * Serviço para gerenciar dados de performance de rotas
 * Fornece métricas, KPIs e dados para visualizações futuristas
 */
@Injectable({
  providedIn: 'root'
})
export class RoutesPerformanceService {
  
  private dashboardDataSubject = new BehaviorSubject<RoutesPerformanceDashboard | null>(null);
  public dashboardData$ = this.dashboardDataSubject.asObservable();

  private filtersSubject = new BehaviorSubject<DashboardFilters>({
    dateRange: {
      start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30 dias atrás
      end: new Date()
    }
  });
  public filters$ = this.filtersSubject.asObservable();

  constructor() {
    this.loadInitialData();
  }

  // ========================================
  // 📊 DADOS PRINCIPAIS
  // ========================================

  /**
   * Carrega dados completos do dashboard
   */
  getDashboardData(filters?: DashboardFilters): Observable<RoutesPerformanceDashboard> {
    // Simular chamada à API com dados mock
    return of(this.generateMockData()).pipe(
      delay(800), // Simular latência da API
      map(data => {
        this.dashboardDataSubject.next(data);
        return data;
      })
    );
  }

  /**
   * Atualiza filtros do dashboard
   */
  updateFilters(filters: Partial<DashboardFilters>): void {
    const currentFilters = this.filtersSubject.value;
    const newFilters = { ...currentFilters, ...filters };
    this.filtersSubject.next(newFilters);
    
    // Recarregar dados com novos filtros
    this.getDashboardData(newFilters).subscribe();
  }

  /**
   * Obtém períodos de tempo disponíveis
   */
  getTimePeriods(): Observable<TimePeriod[]> {
    return of([
      { id: 'today', name: 'Hoje', days: 1, active: false },
      { id: 'current-month', name: 'Mês atual', days: 30, active: true },
      { id: 'current-year', name: 'Ano atual', days: 365, active: false },
      { id: '7d', name: 'Últimos 7 dias', days: 7, active: false },
      { id: '30d', name: 'Últimos 30 dias', days: 30, active: false },
      { id: '90d', name: 'Últimos 90 dias', days: 90, active: false },
      { id: '1y', name: 'Último ano', days: 365, active: false }
    ]);
  }

  // ========================================
  // 🎲 DADOS MOCK PARA DESENVOLVIMENTO
  // ========================================

  private loadInitialData(): void {
    this.getDashboardData().subscribe();
  }

  private generateMockData(): RoutesPerformanceDashboard {
    return {
      routeStatus: this.generateRouteStatusMock(),
      vehicleMetrics: this.generateVehicleMetricsMock(),
      driverMetrics: this.generateDriverMetricsMock(),
      transportModal: this.generateTransportModalMock(),
      operationalMetrics: this.generateOperationalMetricsMock(),
      volumeMetrics: this.generateVolumeMetricsMock(),
      lastUpdated: new Date(),
      refreshInterval: 30000 // 30 segundos
    };
  }

  private generateRouteStatusMock(): RouteStatusMetrics {
    return {
      active: {
        id: 'active',
        name: 'Rotas Ativas',
        count: 245,
        percentage: 35.2,
        trend: 'up',
        trendValue: 12.5,
        color: '#00D4FF',
        icon: 'fas fa-route'
      },
      completed: {
        id: 'completed',
        name: 'Concluídas',
        count: 1847,
        percentage: 52.8,
        trend: 'up',
        trendValue: 8.3,
        color: '#00FF88',
        icon: 'fas fa-check-circle'
      },
      pending: {
        id: 'pending',
        name: 'Pendentes',
        count: 156,
        percentage: 8.9,
        trend: 'down',
        trendValue: -5.2,
        color: '#FF6B35',
        icon: 'fas fa-clock'
      },
      delayed: {
        id: 'delayed',
        name: 'Atrasadas',
        count: 52,
        percentage: 3.1,
        trend: 'down',
        trendValue: -15.7,
        color: '#FF0055',
        icon: 'fas fa-exclamation-triangle'
      },
      total: 2300,
      monthlyTrend: 6.8
    };
  }

  private generateVehicleMetricsMock(): VehicleMetrics {
    const profiles = [
      {
        type: 'truck',
        count: 156,
        percentage: 45.2,
        averageAge: 4.2,
        performanceScore: 87.5,
        mostUsed: true,
        color: '#00D4FF',
        icon: 'fas fa-truck'
      },
      {
        type: 'van',
        count: 89,
        percentage: 25.8,
        averageAge: 3.1,
        performanceScore: 92.1,
        mostUsed: false,
        color: '#8B5CF6',
        icon: 'fas fa-shuttle-van'
      },
      {
        type: 'trailer',
        count: 67,
        percentage: 19.4,
        averageAge: 5.8,
        performanceScore: 78.9,
        mostUsed: false,
        color: '#00FF88',
        icon: 'fas fa-trailer'
      },
      {
        type: 'motorcycle',
        count: 33,
        percentage: 9.6,
        averageAge: 2.5,
        performanceScore: 95.3,
        mostUsed: false,
        color: '#FF6B35',
        icon: 'fas fa-motorcycle'
      }
    ];

    return {
      profiles,
      totalVehicles: 345,
      averageAge: 4.1,
      topPerformer: profiles[3] // motorcycle
    };
  }

  private generateDriverMetricsMock(): DriverMetrics {
    const profiles = [
      {
        gender: 'male' as const,
        count: 278,
        percentage: 72.4,
        averageAge: 38.5,
        performanceScore: 84.2,
        color: '#00D4FF'
      },
      {
        gender: 'female' as const,
        count: 106,
        percentage: 27.6,
        averageAge: 35.8,
        performanceScore: 89.7,
        color: '#8B5CF6'
      }
    ];

    return {
      profiles,
      totalDrivers: 384,
      averageAge: 37.8,
      activeDrivers: 245,
      topPerformers: 89
    };
  }

  private generateTransportModalMock(): TransportModalMetrics {
    const modals = [
      {
        type: 'road' as const,
        name: 'Rodoviário',
        count: 1847,
        percentage: 78.5,
        efficiency: 85.2,
        cost: 2.45,
        color: '#00D4FF',
        icon: 'fas fa-road'
      },
      {
        type: 'rail' as const,
        name: 'Ferroviário',
        count: 312,
        percentage: 13.3,
        efficiency: 92.1,
        cost: 1.89,
        color: '#00FF88',
        icon: 'fas fa-train'
      },
      {
        type: 'multimodal' as const,
        name: 'Multimodal',
        count: 193,
        percentage: 8.2,
        efficiency: 88.7,
        cost: 2.12,
        color: '#8B5CF6',
        icon: 'fas fa-exchange-alt'
      }
    ];

    return {
      modals,
      totalRoutes: 2352,
      mostEfficient: modals[1], // rail
      mostUsed: modals[0] // road
    };
  }

  private generateOperationalMetricsMock(): OperationalMetrics {
    return {
      averageDuration: 8.5, // horas
      totalDistance: 125847, // km
      costs: [
        {
          type: 'fuel',
          name: 'Combustível',
          amount: 89750.50,
          percentage: 52.3,
          trend: 'up',
          trendValue: 8.7,
          color: '#FF6B35',
          icon: 'fas fa-gas-pump'
        },
        {
          type: 'tolls',
          name: 'Pedágios',
          amount: 34250.80,
          percentage: 19.9,
          trend: 'stable',
          trendValue: 0.5,
          color: '#00D4FF',
          icon: 'fas fa-road'
        },
        {
          type: 'maintenance',
          name: 'Manutenção',
          amount: 28450.30,
          percentage: 16.6,
          trend: 'down',
          trendValue: -3.2,
          color: '#8B5CF6',
          icon: 'fas fa-wrench'
        },
        {
          type: 'fines',
          name: 'Multas',
          amount: 12850.75,
          percentage: 7.5,
          trend: 'down',
          trendValue: -12.8,
          color: '#FF0055',
          icon: 'fas fa-exclamation-circle'
        },
        {
          type: 'other',
          name: 'Outros',
          amount: 6420.90,
          percentage: 3.7,
          trend: 'stable',
          trendValue: 1.2,
          color: '#00FF88',
          icon: 'fas fa-ellipsis-h'
        }
      ],
      totalCost: 171723.25,
      costPerKm: 1.36,
      efficiency: 87.4
    };
  }

  private generateVolumeMetricsMock(): VolumeMetrics {
    return {
      totalVolumes: 15847,
      volumesByStatus: {
        active: 3245,
        completed: 11250,
        pending: 987,
        delayed: 365
      },
      averageVolumePerVehicle: 45.9,
      volumeEfficiency: 91.2,
      trend: 'up',
      trendValue: 7.8
    };
  }

  // ========================================
  // 🔄 MÉTODOS UTILITÁRIOS
  // ========================================

  /**
   * Formata números para exibição
   */
  formatNumber(value: number, type: 'currency' | 'percentage' | 'decimal' = 'decimal'): string {
    switch (type) {
      case 'currency':
        return new Intl.NumberFormat('pt-BR', {
          style: 'currency',
          currency: 'BRL'
        }).format(value);
      
      case 'percentage':
        return new Intl.NumberFormat('pt-BR', {
          style: 'percent',
          minimumFractionDigits: 1,
          maximumFractionDigits: 1
        }).format(value / 100);
      
      default:
        return new Intl.NumberFormat('pt-BR').format(value);
    }
  }

  /**
   * Obtém cor baseada na tendência
   */
  getTrendColor(trend: 'up' | 'down' | 'stable'): string {
    switch (trend) {
      case 'up': return '#00FF88';
      case 'down': return '#FF0055';
      default: return '#00D4FF';
    }
  }

  /**
   * Obtém ícone baseado na tendência
   */
  getTrendIcon(trend: 'up' | 'down' | 'stable'): string {
    switch (trend) {
      case 'up': return 'fas fa-arrow-up';
      case 'down': return 'fas fa-arrow-down';
      default: return 'fas fa-minus';
    }
  }
}
