import { Injectable } from '@angular/core';
import { 
  FuelRecord, 
  FuelAnalyticsResult, 
  AnalyticsConfig,
  ProductAnalysis,
  EfficiencyAnalysis,
  DriverAnalysis,
  StationAnalysis,
  ConsumptionAnalysis,
  FuelSummary,
  MonthlyAnalysis,
  BiweeklyAnalysis,
  YearlyAnalysis,
  HeatMapData,
  MonthlyConsumptionChart
} from './fuel-analytics.interface';

/**
 * 🧠 Fuel Analytics Service - Biblioteca de Análise Inteligente
 * 📊 Centraliza todos os cálculos de consumo de combustível
 * 
 * ✨ Features:
 * - Análise por produto/combustível
 * - Análise por motorista
 * - Análise temporal (quinzena, mês, ano)
 * - Análise por posto (mapa de calor)
 * - Cálculos de eficiência
 * - Preparado para ML/IA futuro
 */
@Injectable({
  providedIn: 'root'
})
export class FuelAnalyticsService {

  constructor() {}

  // ========================================
  // 🎯 MÉTODO PRINCIPAL - ANÁLISE COMPLETA
  // ========================================

  /**
   * 🚀 Análise completa dos dados de combustível
   * @param records Array de registros de abastecimento
   * @param config Configurações opcionais de análise
   * @returns Resultado completo com todas as análises
   */
  analyzeData(records: FuelRecord[], config: AnalyticsConfig = {}): FuelAnalyticsResult {
    const startTime = performance.now();
    
    // Filtrar e preparar dados
    const filteredRecords = this.filterRecords(records, config);
    const sortedRecords = this.sortRecordsByDate(filteredRecords);
    
    // Executar todas as análises
    const result: FuelAnalyticsResult = {
      summary: this.calculateSummary(sortedRecords),
      consumption: this.calculateConsumption(sortedRecords),
      products: this.analyzeProducts(sortedRecords),
      efficiency: this.analyzeEfficiency(sortedRecords),
      drivers: this.analyzeDrivers(sortedRecords),
      temporal: {
        biweekly: this.analyzeBiweekly(sortedRecords),
        monthly: this.analyzeMonthly(sortedRecords),
        yearly: this.analyzeYearly(sortedRecords)
      },
      stations: this.analyzeStations(sortedRecords),
      heatMap: this.generateHeatMap(sortedRecords),
      config,
      generatedAt: new Date(),
      processingTime: performance.now() - startTime
    };

    console.log(`🧠 Fuel Analytics: Processados ${sortedRecords.length} registros em ${result.processingTime.toFixed(2)}ms`);
    
    return result;
  }

  // ========================================
  // 🔧 MÉTODOS DE PREPARAÇÃO DE DADOS
  // ========================================

  private filterRecords(records: FuelRecord[], config: AnalyticsConfig): FuelRecord[] {
    let filtered = records.filter(record => {
      // Filtrar apenas aprovados por padrão
      if (!config.includeRejected && record.status !== 'SUPPLY_APPROVED') {
        return false;
      }

      // Filtrar por data
      if (config.dateRange) {
        const recordDate = new Date(record.date);
        if (recordDate < config.dateRange.start || recordDate > config.dateRange.end) {
          return false;
        }
      }

      // Filtrar por veículo
      if (config.vehicleIds && !config.vehicleIds.includes(record.vehicleId)) {
        return false;
      }

      // Filtrar por motorista
      if (config.driverIds && !config.driverIds.includes(record.personId)) {
        return false;
      }

      return true;
    });

    // Aplicar limite se especificado
    if (config.limit) {
      filtered = filtered.slice(0, config.limit);
    }

    return filtered;
  }

  private sortRecordsByDate(records: FuelRecord[]): FuelRecord[] {
    return [...records].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
  }

  // ========================================
  // 📊 ANÁLISE POR PRODUTO/COMBUSTÍVEL
  // ========================================

  analyzeProducts(records: FuelRecord[]): ProductAnalysis[] {
    const productStats: { [key: string]: { totalValue: number, totalQuantity: number, count: number } } = {};
    let grandTotalValue = 0;
    
    records.forEach(record => {
      record.items?.forEach(item => {
        const productName = item.productName || 'Produto não informado';
        
        if (!productStats[productName]) {
          productStats[productName] = { totalValue: 0, totalQuantity: 0, count: 0 };
        }
        
        const itemValue = parseFloat(item.value?.toString() || '0');
        const itemQuantity = parseFloat((item.quantity || item.liters)?.toString() || '0');
        
        productStats[productName].totalValue += itemValue;
        productStats[productName].totalQuantity += itemQuantity;
        productStats[productName].count++;
        grandTotalValue += itemValue;
      });
    });
    
    return Object.entries(productStats)
      .map(([productName, stats]) => ({
        productName,
        totalValue: stats.totalValue,
        totalQuantity: stats.totalQuantity,
        avgPricePerLiter: stats.totalQuantity > 0 ? stats.totalValue / stats.totalQuantity : 0,
        count: stats.count,
        percentage: grandTotalValue > 0 ? (stats.totalValue / grandTotalValue) * 100 : 0
      }))
      .sort((a, b) => b.totalValue - a.totalValue);
  }

  // ========================================
  // ⚡ ANÁLISE DE EFICIÊNCIA
  // ========================================

  analyzeEfficiency(records: FuelRecord[]): EfficiencyAnalysis[] {
    if (records.length < 2) return [];

    const sorted = [...records].sort((a, b) => a.odometer - b.odometer);
    const fuelEfficiency: { [key: string]: number[] } = {};
    
    for (let i = 1; i < sorted.length; i++) {
      const current = sorted[i];
      const previous = sorted[i - 1];
      
      const kmDiff = current.odometer - previous.odometer;
      
      if (kmDiff > 0) {
        current.items?.forEach(item => {
          const productName = item.productName || 'Produto não informado';
          const itemQuantity = parseFloat((item.quantity || item.liters)?.toString() || '0');
          
          if (itemQuantity > 0) {
            const consumptionPer100km = (itemQuantity / kmDiff) * 100;
            
            // Filtrar valores absurdos (entre 1 e 50 L/100km)
            if (consumptionPer100km > 1 && consumptionPer100km < 50) {
              if (!fuelEfficiency[productName]) {
                fuelEfficiency[productName] = [];
              }
              fuelEfficiency[productName].push(consumptionPer100km);
            }
          }
        });
      }
    }
    
    return Object.entries(fuelEfficiency)
      .map(([productName, consumptionData]) => {
        if (consumptionData.length === 0) {
          return {
            productName,
            avgConsumption: 0,
            bestEfficiency: 0,
            worstEfficiency: 0,
            samplesCount: 0
          };
        }
        
        const avgConsumption = consumptionData.reduce((sum, c) => sum + c, 0) / consumptionData.length;
        const bestEfficiency = Math.min(...consumptionData);   // Menor consumo = Melhor
        const worstEfficiency = Math.max(...consumptionData);  // Maior consumo = Pior
        
        return {
          productName,
          avgConsumption,
          bestEfficiency,
          worstEfficiency,
          samplesCount: consumptionData.length
        };
      })
      .filter(item => item.samplesCount > 0)
      .sort((a, b) => a.avgConsumption - b.avgConsumption); // Melhor eficiência primeiro
  }

  // ========================================
  // 👨‍💼 ANÁLISE POR MOTORISTA
  // ========================================

  analyzeDrivers(records: FuelRecord[]): DriverAnalysis[] {
    const driverStats: { [key: number]: {
      name: string,
      totalValue: number,
      totalQuantity: number,
      count: number,
      consumptionData: number[],
      fuelBreakdown: { [fuel: string]: { value: number, quantity: number, count: number } },
      maxSingleValue: number,
      odometerReadings: number[]
    } } = {};
    
    // Processar registros por motorista
    records.forEach(record => {
      const driverId = record.personId;
      const driverName = record.personName || 'Motorista não informado';
      
      if (!driverStats[driverId]) {
        driverStats[driverId] = {
          name: driverName,
          totalValue: 0,
          totalQuantity: 0,
          count: 0,
          consumptionData: [],
          fuelBreakdown: {},
          maxSingleValue: 0,
          odometerReadings: []
        };
      }
      
      const driver = driverStats[driverId];
      
      // 🆕 Calcular valor total do abastecimento para encontrar o maior valor
      const recordTotalValue = parseFloat(record.value?.toString() || '0');
      if (recordTotalValue > driver.maxSingleValue) {
        driver.maxSingleValue = recordTotalValue;
      }
      
      // 🆕 Armazenar leituras do odômetro para calcular KM total
      if (record.odometer && record.odometer > 0) {
        driver.odometerReadings.push(record.odometer);
      }
      
      record.items?.forEach(item => {
        const itemValue = parseFloat(item.value?.toString() || '0');
        const itemQuantity = parseFloat((item.quantity || item.liters)?.toString() || '0');
        const fuelType = item.productName || 'Produto não informado';
        
        driver.totalValue += itemValue;
        driver.totalQuantity += itemQuantity;
        driver.count++;
        
        // Breakdown por combustível
        if (!driver.fuelBreakdown[fuelType]) {
          driver.fuelBreakdown[fuelType] = { value: 0, quantity: 0, count: 0 };
        }
        driver.fuelBreakdown[fuelType].value += itemValue;
        driver.fuelBreakdown[fuelType].quantity += itemQuantity;
        driver.fuelBreakdown[fuelType].count++;
      });
    });
    
    // Calcular eficiência por motorista
    const driverRecords = this.groupRecordsByDriver(records);
    
    return Object.entries(driverStats).map(([driverIdStr, stats]) => {
      const driverId = parseInt(driverIdStr);
      const driverRecordsForEfficiency = driverRecords[driverId] || [];
      const efficiencyData = this.calculateDriverEfficiency(driverRecordsForEfficiency);
      
      // Converter breakdown para formato da interface
      const fuelBreakdown: ProductAnalysis[] = Object.entries(stats.fuelBreakdown).map(([fuelType, data]) => ({
        productName: fuelType,
        totalValue: data.value,
        totalQuantity: data.quantity,
        avgPricePerLiter: data.quantity > 0 ? data.value / data.quantity : 0,
        count: data.count,
        percentage: stats.totalValue > 0 ? (data.value / stats.totalValue) * 100 : 0
      }));
      
      // 🆕 Calcular total de KM percorridos
      const sortedOdometer = stats.odometerReadings.sort((a, b) => a - b);
      const totalKilometers = sortedOdometer.length > 1 
        ? sortedOdometer[sortedOdometer.length - 1] - sortedOdometer[0]
        : 0;
      
      return {
        driverName: stats.name,
        driverId,
        totalValue: stats.totalValue,
        totalQuantity: stats.totalQuantity,
        totalSupplies: stats.count,
        avgConsumption: efficiencyData.avgConsumption,
        bestEfficiency: efficiencyData.bestEfficiency,
        worstEfficiency: efficiencyData.worstEfficiency,
        fuelBreakdown,
        performanceRating: this.calculatePerformanceRating(efficiencyData.avgConsumption),
        // 🆕 Novos campos
        maxSingleValue: stats.maxSingleValue,
        totalKilometers,
        trendsLast30Days: {
          valueChange: 0, // TODO: Implementar cálculo de tendência
          quantityChange: 0,
          efficiencyChange: 0
        }
      };
    }).sort((a, b) => b.totalValue - a.totalValue);
  }

  private groupRecordsByDriver(records: FuelRecord[]): { [driverId: number]: FuelRecord[] } {
    return records.reduce((groups, record) => {
      const driverId = record.personId;
      if (!groups[driverId]) {
        groups[driverId] = [];
      }
      groups[driverId].push(record);
      return groups;
    }, {} as { [driverId: number]: FuelRecord[] });
  }

  private calculateDriverEfficiency(records: FuelRecord[]): { avgConsumption: number, bestEfficiency: number, worstEfficiency: number } {
    if (records.length < 2) {
      return { avgConsumption: 0, bestEfficiency: 0, worstEfficiency: 0 };
    }

    const sorted = [...records].sort((a, b) => a.odometer - b.odometer);
    const consumptionData: number[] = [];
    
    for (let i = 1; i < sorted.length; i++) {
      const current = sorted[i];
      const previous = sorted[i - 1];
      
      const kmDiff = current.odometer - previous.odometer;
      const totalLiters = current.items?.reduce((sum, item) => {
        return sum + parseFloat((item.quantity || item.liters)?.toString() || '0');
      }, 0) || 0;
      
      if (kmDiff > 0 && totalLiters > 0) {
        const consumptionPer100km = (totalLiters / kmDiff) * 100;
        if (consumptionPer100km > 0 && consumptionPer100km < 50) {
          consumptionData.push(consumptionPer100km);
        }
      }
    }
    
    if (consumptionData.length === 0) {
      return { avgConsumption: 0, bestEfficiency: 0, worstEfficiency: 0 };
    }
    
    const avgConsumption = consumptionData.reduce((sum, c) => sum + c, 0) / consumptionData.length;
    const bestEfficiency = Math.min(...consumptionData);
    const worstEfficiency = Math.max(...consumptionData);
    
    return { avgConsumption, bestEfficiency, worstEfficiency };
  }

  private calculatePerformanceRating(avgConsumption: number): 'excellent' | 'good' | 'average' | 'poor' {
    if (avgConsumption <= 8) return 'excellent';
    if (avgConsumption <= 12) return 'good';
    if (avgConsumption <= 16) return 'average';
    return 'poor';
  }

  // ========================================
  // 📅 ANÁLISES TEMPORAIS
  // ========================================

  analyzeMonthly(records: FuelRecord[]): MonthlyAnalysis[] {
    const monthlyStats: { [key: string]: FuelRecord[] } = {};
    
    records.forEach(record => {
      const date = new Date(record.date);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      
      if (!monthlyStats[monthKey]) {
        monthlyStats[monthKey] = [];
      }
      monthlyStats[monthKey].push(record);
    });
    
    return Object.entries(monthlyStats).map(([monthKey, monthRecords]) => {
      const [year, month] = monthKey.split('-').map(Number);
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0);
      
      return {
        period: monthKey,
        month,
        year,
        startDate,
        endDate,
        totalValue: this.calculateTotalValue(monthRecords),
        totalQuantity: this.calculateTotalQuantity(monthRecords),
        totalSupplies: monthRecords.length,
        avgConsumption: this.calculateAvgConsumption(monthRecords),
        totalKilometers: this.calculateTotalKilometers(monthRecords), // 🆕 Total de KM
        fuelBreakdown: this.analyzeProducts(monthRecords),
        topDrivers: this.analyzeDrivers(monthRecords).slice(0, 5),
        topStations: this.analyzeStations(monthRecords).slice(0, 5)
      };
    }).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
  }

  analyzeBiweekly(records: FuelRecord[]): BiweeklyAnalysis[] {
    // TODO: Implementar análise quinzenal
    return [];
  }

  analyzeYearly(records: FuelRecord[]): YearlyAnalysis[] {
    // TODO: Implementar análise anual
    return [];
  }

  // ========================================
  // ⛽ ANÁLISE POR POSTO
  // ========================================

  analyzeStations(records: FuelRecord[]): StationAnalysis[] {
    const stationStats: { [key: string]: {
      name: string,
      brand: string,
      supplierId: number,
      lat: number,
      lon: number,
      totalValue: number,
      totalQuantity: number,
      count: number,
      lastDate: Date,
      drivers: Set<number>
    } } = {};
    
    records.forEach(record => {
      const stationKey = `${record.supplierId}-${record.supplierName}`;
      
      if (!stationStats[stationKey]) {
        stationStats[stationKey] = {
          name: record.supplierName,
          brand: record.gasStationBrand,
          supplierId: record.supplierId,
          lat: parseFloat(record.lat),
          lon: parseFloat(record.lon),
          totalValue: 0,
          totalQuantity: 0,
          count: 0,
          lastDate: new Date(record.date),
          drivers: new Set()
        };
      }
      
      const station = stationStats[stationKey];
      
      record.items?.forEach(item => {
        const itemValue = parseFloat(item.value?.toString() || '0');
        const itemQuantity = parseFloat((item.quantity || item.liters)?.toString() || '0');
        
        station.totalValue += itemValue;
        station.totalQuantity += itemQuantity;
      });
      
      station.count++;
      station.drivers.add(record.personId);
      
      const recordDate = new Date(record.date);
      if (recordDate > station.lastDate) {
        station.lastDate = recordDate;
      }
    });
    
    const maxCount = Math.max(...Object.values(stationStats).map(s => s.count));
    
    return Object.entries(stationStats).map(([key, stats]) => ({
      stationName: stats.name,
      stationBrand: stats.brand,
      supplierId: stats.supplierId,
      location: {
        lat: stats.lat,
        lon: stats.lon
      },
      totalValue: stats.totalValue,
      totalQuantity: stats.totalQuantity,
      totalSupplies: stats.count,
      avgPricePerLiter: stats.totalQuantity > 0 ? stats.totalValue / stats.totalQuantity : 0,
      fuelBreakdown: this.analyzeProducts(records.filter(r => r.supplierId === stats.supplierId)),
      frequencyScore: maxCount > 0 ? (stats.count / maxCount) * 100 : 0,
      lastSupplyDate: stats.lastDate,
      driverFrequency: {} // TODO: Implementar frequência por motorista
    })).sort((a, b) => b.totalValue - a.totalValue);
  }

  // ========================================
  // 🗺️ MAPA DE CALOR
  // ========================================

  generateHeatMap(records: FuelRecord[]): HeatMapData {
    const stations = this.analyzeStations(records);
    
    if (stations.length === 0) {
      return {
        stations: [],
        bounds: { north: 0, south: 0, east: 0, west: 0 },
        clusters: []
      };
    }
    
    const lats = stations.map(s => s.location.lat).filter(lat => !isNaN(lat));
    const lons = stations.map(s => s.location.lon).filter(lon => !isNaN(lon));
    
    const bounds = {
      north: Math.max(...lats),
      south: Math.min(...lats),
      east: Math.max(...lons),
      west: Math.min(...lons)
    };
    
    // Gerar clusters para mapa de calor
    const clusters = stations.map(station => ({
      lat: station.location.lat,
      lon: station.location.lon,
      weight: station.frequencyScore,
      stationCount: 1
    }));
    
    return {
      stations,
      bounds,
      clusters
    };
  }

  // ========================================
  // 📈 MÉTODOS PARA GRÁFICOS
  // ========================================

  /**
   * 📊 Gerar dados para gráfico de consumo mensal
   * @param records Array de registros de combustível
   * @returns Dados formatados para gráficos (Chart.js, etc.)
   */
  getMonthlyConsumptionChart(records: FuelRecord[]): MonthlyConsumptionChart {
    const monthlyData = this.analyzeMonthly(records);
    
    if (monthlyData.length === 0) {
      return {
        totalConsumption: { labels: [], datasets: [] },
        byFuelType: { labels: [], datasets: [] },
        summary: {
          totalMonths: 0,
          totalValue: 0,
          totalQuantity: 0,
          avgMonthlyConsumption: 0,
          peakMonth: { month: '', value: 0, quantity: 0 },
          lowMonth: { month: '', value: 0, quantity: 0 }
        }
      };
    }

    // Ordenar por data
    const sortedMonthly = monthlyData.sort((a, b) => 
      new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
    );

    // Labels dos meses (formato brasileiro)
    const labels = sortedMonthly.map(month => {
      const date = new Date(month.startDate);
      return date.toLocaleDateString('pt-BR', { month: 'short', year: 'numeric' });
    });

    // Dados de consumo total
    const totalConsumptionData = sortedMonthly.map(month => month.totalQuantity);
    const totalValueData = sortedMonthly.map(month => month.totalValue);

    // Coletar todos os tipos de combustível únicos
    const allFuelTypes = new Set<string>();
    sortedMonthly.forEach(month => {
      month.fuelBreakdown.forEach(fuel => {
        allFuelTypes.add(fuel.productName);
      });
    });

    // Cores para diferentes combustíveis
    const fuelColors: { [key: string]: { bg: string, border: string } } = {
      'Diesel S-10 Comum': { bg: 'rgba(54, 162, 235, 0.6)', border: 'rgba(54, 162, 235, 1)' },
      'Etanol Comum': { bg: 'rgba(75, 192, 192, 0.6)', border: 'rgba(75, 192, 192, 1)' },
      'Gasolina Comum': { bg: 'rgba(255, 206, 86, 0.6)', border: 'rgba(255, 206, 86, 1)' },
      'Arla 32 - Granel': { bg: 'rgba(153, 102, 255, 0.6)', border: 'rgba(153, 102, 255, 1)' },
      'Diesel S-500': { bg: 'rgba(255, 159, 64, 0.6)', border: 'rgba(255, 159, 64, 1)' }
    };

    // Cores padrão para combustíveis não mapeados
    const defaultColors = [
      { bg: 'rgba(255, 99, 132, 0.6)', border: 'rgba(255, 99, 132, 1)' },
      { bg: 'rgba(54, 162, 235, 0.6)', border: 'rgba(54, 162, 235, 1)' },
      { bg: 'rgba(255, 205, 86, 0.6)', border: 'rgba(255, 205, 86, 1)' },
      { bg: 'rgba(75, 192, 192, 0.6)', border: 'rgba(75, 192, 192, 1)' },
      { bg: 'rgba(153, 102, 255, 0.6)', border: 'rgba(153, 102, 255, 1)' }
    ];

    // Gerar datasets por tipo de combustível
    const fuelDatasets = Array.from(allFuelTypes).map((fuelType, index) => {
      const data = sortedMonthly.map(month => {
        const fuelData = month.fuelBreakdown.find(fuel => fuel.productName === fuelType);
        return fuelData ? fuelData.totalQuantity : 0;
      });

      const colors = fuelColors[fuelType] || defaultColors[index % defaultColors.length];

      return {
        label: fuelType,
        data,
        backgroundColor: colors.bg,
        borderColor: colors.border
      };
    });

    // Calcular estatísticas do resumo
    const totalValue = sortedMonthly.reduce((sum, month) => sum + month.totalValue, 0);
    const totalQuantity = sortedMonthly.reduce((sum, month) => sum + month.totalQuantity, 0);
    const avgMonthlyConsumption = totalQuantity / sortedMonthly.length;

    // Encontrar pico e vale
    const peakMonth = sortedMonthly.reduce((peak, current) => 
      current.totalQuantity > peak.totalQuantity ? current : peak
    );
    const lowMonth = sortedMonthly.reduce((low, current) => 
      current.totalQuantity < low.totalQuantity ? current : low
    );

    return {
      totalConsumption: {
        labels,
        datasets: [
          {
            label: 'Consumo Total (Litros)',
            data: totalConsumptionData,
            backgroundColor: 'rgba(54, 162, 235, 0.6)',
            borderColor: 'rgba(54, 162, 235, 1)'
          },
          {
            label: 'Valor Total (R$)',
            data: totalValueData,
            backgroundColor: 'rgba(255, 99, 132, 0.6)',
            borderColor: 'rgba(255, 99, 132, 1)'
          }
        ]
      },
      byFuelType: {
        labels,
        datasets: fuelDatasets
      },
      summary: {
        totalMonths: sortedMonthly.length,
        totalValue,
        totalQuantity,
        avgMonthlyConsumption,
        peakMonth: {
          month: new Date(peakMonth.startDate).toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' }),
          value: peakMonth.totalValue,
          quantity: peakMonth.totalQuantity
        },
        lowMonth: {
          month: new Date(lowMonth.startDate).toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' }),
          value: lowMonth.totalValue,
          quantity: lowMonth.totalQuantity
        }
      }
    };
  }

  // ========================================
  // 🧮 MÉTODOS AUXILIARES DE CÁLCULO
  // ========================================

  private calculateSummary(records: FuelRecord[]): FuelSummary {
    const products = this.analyzeProducts(records);
    const drivers = this.analyzeDrivers(records);
    const stations = this.analyzeStations(records);
    
    const dates = records.map(r => new Date(r.date)).sort((a, b) => a.getTime() - b.getTime());
    const dateRange = dates.length > 0 ? {
      start: dates[0],
      end: dates[dates.length - 1],
      days: Math.ceil((dates[dates.length - 1].getTime() - dates[0].getTime()) / (1000 * 60 * 60 * 24))
    } : { start: new Date(), end: new Date(), days: 0 };
    
    return {
      totalProducts: products.length,
      totalValue: this.calculateTotalValue(records),
      totalQuantity: this.calculateTotalQuantity(records),
      totalSupplies: records.length,
      avgPricePerLiter: this.calculateAvgPricePerLiter(records),
      mostUsedFuel: products.length > 0 ? products[0].productName : 'Nenhum',
      mostEfficientDriver: drivers.length > 0 ? drivers.find(d => d.performanceRating === 'excellent')?.driverName || drivers[0].driverName : 'Nenhum',
      mostFrequentStation: stations.length > 0 ? stations[0].stationName : 'Nenhum',
      dateRange
    };
  }

  private calculateConsumption(records: FuelRecord[]): ConsumptionAnalysis {
    const efficiency = this.analyzeEfficiency(records);
    const overallEfficiency = efficiency.length > 0 ? 
      efficiency.reduce((sum, e) => sum + e.avgConsumption, 0) / efficiency.length : 0;
    
    const bestOverall = efficiency.length > 0 ? Math.min(...efficiency.map(e => e.bestEfficiency)) : 0;
    const worstOverall = efficiency.length > 0 ? Math.max(...efficiency.map(e => e.worstEfficiency)) : 0;
    const totalSamples = efficiency.reduce((sum, e) => sum + e.samplesCount, 0);
    
    return {
      avgConsumption: overallEfficiency,
      bestEfficiency: bestOverall,
      worstEfficiency: worstOverall,
      trend: 'stable', // TODO: Implementar cálculo de tendência
      samplesCount: totalSamples
    };
  }

  private calculateTotalValue(records: FuelRecord[]): number {
    return records.reduce((total, record) => {
      return total + record.items.reduce((itemTotal, item) => {
        return itemTotal + parseFloat(item.value?.toString() || '0');
      }, 0);
    }, 0);
  }

  private calculateTotalQuantity(records: FuelRecord[]): number {
    return records.reduce((total, record) => {
      return total + record.items.reduce((itemTotal, item) => {
        return itemTotal + parseFloat((item.quantity || item.liters)?.toString() || '0');
      }, 0);
    }, 0);
  }

  private calculateAvgPricePerLiter(records: FuelRecord[]): number {
    const totalValue = this.calculateTotalValue(records);
    const totalQuantity = this.calculateTotalQuantity(records);
    return totalQuantity > 0 ? totalValue / totalQuantity : 0;
  }

  private calculateAvgConsumption(records: FuelRecord[]): number {
    const efficiency = this.analyzeEfficiency(records);
    return efficiency.length > 0 ? 
      efficiency.reduce((sum, e) => sum + e.avgConsumption, 0) / efficiency.length : 0;
  }

  /**
   * 🆕 Calcular total de quilômetros percorridos
   * @param records Array de registros de combustível
   * @returns Total de KM percorridos no período
   */
  private calculateTotalKilometers(records: FuelRecord[]): number {
    if (records.length < 2) return 0;
    
    // Filtrar registros com odômetro válido e ordenar por odômetro
    const validRecords = records
      .filter(record => record.odometer && record.odometer > 0)
      .sort((a, b) => a.odometer - b.odometer);
    
    if (validRecords.length < 2) return 0;
    
    // Calcular diferença entre maior e menor odômetro
    const maxOdometer = validRecords[validRecords.length - 1].odometer;
    const minOdometer = validRecords[0].odometer;
    
    return maxOdometer - minOdometer;
  }
}
