import { Component, Input, OnInit, ChangeDetectorRef, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
import { Observable, BehaviorSubject, switchMap, tap, catchError, of, map } from 'rxjs';

import { FuelcontrollService } from '../../../fuelcontroll/fuelcontroll.service';
import { Fuelcontroll } from '../../../fuelcontroll/fuelcontroll.interface';
import { Vehicle } from '../../vehicle.interface';
import { DataTableComponent, Column } from '../../../../shared/components/data-table/data-table.component';
import { PaginatedResponse } from '../../../../shared/interfaces/paginate.interface';

// 🧠 Nova biblioteca de análise de combustível
import { 
  FuelAnalyticsService, 
  FuelAnalyticsResult, 
  FuelRecord,
  ProductAnalysis,
  EfficiencyAnalysis,
  DriverAnalysis,
  StationAnalysis
} from '../../../../shared/services/fuel-analytics';

/**
 * 🚗⛽ VehicleFuelcontrollComponent - Lista de Abastecimentos por Veículo
 * 
 * ✨ Componente para exibir histórico de abastecimentos de um veículo específico
 * 🎯 Integrado na aba "Abastecimento" do veículo
 */
@Component({
  selector: 'app-vehicle-fuelcontroll',
  standalone: true,
  imports: [CommonModule, DataTableComponent],
  providers: [DatePipe],
  templateUrl: './vehicle-fuelcontroll.component.html',
  styleUrl: './vehicle-fuelcontroll.component.scss'
})
export class VehicleFuelcontrollComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() vehicleData: Vehicle | undefined;
  fuelcontrollRecords$: Observable<Fuelcontroll[]>;
  records: Fuelcontroll[] = []; // ✅ Array para análises
  loading = false;
  hasError = false;
  
  // 🧠 Dados da nova biblioteca de análise
  analyticsResult: FuelAnalyticsResult | null = null;
  
  
  // 📊 Cache para análise mensal (evitar loop infinito)
  private _monthlyAnalysis: { month: string, total: number, liters: number, count: number, totalKilometers: number }[] = [];
  
  // 📊 Cache para outras análises (evitar loops infinitos)
  private _driverAnalysis: DriverAnalysis[] = [];
  private _productAnalysis: ProductAnalysis[] = [];
  private _efficiencyAnalysis: EfficiencyAnalysis[] = [];
  private _fuelSummary: any = null;
  private _supplierAnalysis: { supplierName: string, totalValue: number, totalLiters: number, count: number }[] = [];
  private _gasStationAnalysis: { gasStationName: string, totalValue: number, totalLiters: number, count: number }[] = [];
  
  
  private vehicleIdSubject = new BehaviorSubject<number | null>(null);
  private _initialData: Vehicle | undefined;
  
  @Input() set initialData(data: Vehicle | undefined) {
    this._initialData = data;
    if (data?.id) {
      this.vehicleIdSubject.next(data.id);
    }
  }
  
  // ========================================
  // 🏗️ CONFIGURAÇÃO DA TABELA
  // ========================================
  
  columns: Column[] = [
    { 
      field: "id", 
      header: "ID", 
      sortable: true, 
      filterable: false,
      width: "80px"
    },
    { 
      field: "code", 
      header: "Código", 
      sortable: true, 
      filterable: false,
      width: "120px"
    },
    {
      field: "date",
      header: "Data",
      sortable: true,
      filterable: false,
      width: "120px",
      label: (date: string) => this.datePipe.transform(date, "dd/MM/yyyy") || "-"
    },
    { 
      field: "personName", 
      header: "Motorista", 
      sortable: true, 
      filterable: false 
    },
    { 
      field: "supplierName", 
      header: "Fornecedor", 
      sortable: true, 
      filterable: false,
      width: "200px"
    },
    { 
      field: "gasStationBrand", 
      header: "Marca do Posto", 
      sortable: true, 
      filterable: false,
      width: "150px"
    },
    {
      field: "value",
      header: "Valor (R$)",
      sortable: true,
      filterable: false,
      width: "120px",
      label: (value: any) => {
        if (!value) return '-';
        return `R$ ${parseFloat(value.toString()).toFixed(2)}`;
      }
    },
    {
      field: "odometer",
      header: "Odômetro",
      sortable: true,
      filterable: false,
      width: "120px",
      label: (odometer: number) => odometer ? `${odometer.toLocaleString('pt-BR')} km` : "-"
    },
    {
      field: "status",
      header: "Status",
      sortable: true,
      filterable: false,
      allowHtml: true,
      width: "120px",
      label: (value: any) => {
        const statusConfig: { [key: string]: { label: string, class: string } } = {
          'SUPPLY_APPROVED': { label: 'Aprovado', class: 'status-approved' },
          'SUPPLY_REJECTED': { label: 'Rejeitado', class: 'status-rejected' },
          'SUPPLY_PENDING': { label: 'Pendente', class: 'status-pending' }
        };
        const config = statusConfig[value] || { label: value, class: 'status-unknown' };
        return `<span class="status-badge ${config.class}">${config.label}</span>`;
      }
    }
  ];

  // ✅ NOVO: Expor Math para uso no template
  Math = Math;

  /**
   * 📅 Converter período para nome do mês em português
   */
  getMonthName(period: string): string {
    const [year, month] = period.split('-');
    const date = new Date(parseInt(year), parseInt(month) - 1, 1);
    
    return date.toLocaleDateString('pt-BR', { 
      month: 'long', 
      year: 'numeric' 
    });
  }

  constructor(
    private fuelcontrollService: FuelcontrollService,
    private datePipe: DatePipe,
    private cdr: ChangeDetectorRef,
    private fuelAnalytics: FuelAnalyticsService // 🧠 Nova biblioteca
  ) {
    
    this.fuelcontrollRecords$ = this.vehicleIdSubject.pipe(
      switchMap(vehicleId => {        
        if (!vehicleId) {
          return of([]);
        }

        this.loading = true;
        this.hasError = false;
        this.cdr.detectChanges();

        // 🎯 Filtrar abastecimentos por veículo
        return this.fuelcontrollService.getFuelcontrolls(1, 100, { vehicleIds: vehicleId.toString() , status: 'SUPPLY_APPROVED'}).pipe(
          map((response: PaginatedResponse<Fuelcontroll>) => response?.data || []), // Extrair dados da resposta paginada
          tap((data: Fuelcontroll[]) => {
            this.records = data; // ✅ Atualizar array para análises
            
            // 🧠 Processar dados com a nova biblioteca
            if (data.length > 0) {
              this.processAnalytics(data);
            }
            
            this.loading = false;
            this.cdr.detectChanges();
          }),
          catchError(error => {
            console.error('Erro ao carregar abastecimentos:', error);
            this.loading = false;
            this.hasError = true;
            this.cdr.detectChanges();
            return of([]);
          })
        );
      })
    );
  }

  ngOnInit() {
    if (this._initialData?.id) {
      this.vehicleIdSubject.next(this._initialData.id);
    }
  }

  ngAfterViewInit() {
    // Componente inicializado
  }

  ngOnDestroy() {
    // Limpeza se necessário
  }

  retryLoad() {
    if (this._initialData?.id) {
      this.hasError = false;
      this.vehicleIdSubject.next(this._initialData.id);
    }
  }

  // ========================================
  // 🧠 PROCESSAMENTO COM NOVA BIBLIOTECA
  // ========================================

  /**
   * 🚀 Processar dados com a biblioteca de análise
   */
  private processAnalytics(data: Fuelcontroll[]): void {
    try {
      // Converter dados para o formato da biblioteca
      const fuelRecords: FuelRecord[] = data.map(record => ({
        id: record.id,
        personId: record.personId || 0,
        vehicleId: record.vehicleId,
        supplierId: record.supplierId || 0,
        companyId: record.companyId || 0,
        code: record.code || '',
        status: record.status || '',
        lat: record.lat?.toString() || '0',
        lon: record.lon?.toString() || '0',
        gasStationBrand: record.gasStationBrand || '',
        value: record.value?.toString() || '0',
        odometer: record.odometer || 0,
        date: record.date || new Date().toISOString(),
        personName: (record as any).personName || 'Motorista não informado',
        licensePlate: (record as any).licensePlate || '',
        vehicleModel: (record as any).vehicleModel || '',
        supplierName: (record as any).supplierName || '',
        companyName: (record as any).companyName || '',
        items: (record.items || []).map(item => ({
          productId: item.productId,
          productName: item.productName || 'Produto não informado',
          productCode: item.productCode || '',
          value: item.value?.toString() || '0',
          quantity: item.quantity?.toString() || '0',
          liters: item.liters?.toString()
        }))
      }));

      // Processar com a biblioteca
      this.analyticsResult = this.fuelAnalytics.analyzeData(fuelRecords, {
        includeRejected: false,
        sortBy: 'date',
        sortOrder: 'desc'
      });


      // 📊 Gerar análise mensal e cachear
      const monthly = this.analyticsResult?.temporal.monthly || [];
      this._monthlyAnalysis = monthly.map(month => ({
        month: month.period,
        total: month.totalValue,
        liters: month.totalQuantity,
        count: month.totalSupplies,
        totalKilometers: month.totalKilometers // 🆕 Total de KM
      }));

      // 📊 Cachear outras análises
      this._driverAnalysis = this.analyticsResult?.drivers || [];
      this._productAnalysis = this.analyticsResult?.products || [];
      this._efficiencyAnalysis = this.analyticsResult?.efficiency || [];
      this._fuelSummary = this.analyticsResult?.summary || {
        totalProducts: 0,
        totalValue: 0,
        totalQuantity: 0,
        avgPricePerLiter: 0,
        mostUsedFuel: 'Nenhum',
        totalSupplies: 0
      };

      // 📊 Processar análise por fornecedor/posto
      this._supplierAnalysis = this.processSupplierAnalysis(data);
      this._gasStationAnalysis = this.processGasStationAnalysis(data);

      console.log('🧠 Analytics Result:', this.analyticsResult);
      console.log('📊 Monthly Analysis:', this._monthlyAnalysis);
      
    } catch (error) {
      console.error('❌ Erro ao processar analytics:', error);
    }
  }

  // ========================================
  // 📊 MÉTODOS USANDO A NOVA BIBLIOTECA
  // ========================================

  getRecordCount(records: Fuelcontroll[]): number {
    return this._fuelSummary?.totalSupplies || records?.length || 0;
  }

  getTotalValue(records: Fuelcontroll[]): number {
    return this._fuelSummary?.totalValue || 0;
  }

  getLastFuel(records: Fuelcontroll[]): Fuelcontroll | null {
    if (!records?.length) return null;
    
    return records.reduce((latest, current) => {
      const latestDate = new Date(latest.date || 0);
      const currentDate = new Date(current.date || 0);
      return currentDate > latestDate ? current : latest;
    });
  }

  /**
   * 📊 Obter análise de produtos (cached)
   */
  get productAnalysis(): ProductAnalysis[] {
    return this._productAnalysis;
  }

  /**
   * 📊 Obter análise de eficiência (cached)
   */
  get efficiencyAnalysis(): EfficiencyAnalysis[] {
    return this._efficiencyAnalysis;
  }

  /**
   * 📊 Obter análise de motoristas (cached)
   */
  get driverAnalysis(): DriverAnalysis[] {
    return this._driverAnalysis;
  }

  /**
   * 📊 Obter análise mensal (cached)
   */
  get monthlyAnalysis(): { month: string, total: number, liters: number, count: number, totalKilometers: number }[] {
    return this._monthlyAnalysis;
  }

  /**
   * 📊 Obter resumo de combustível (cached)
   */
  get fuelSummary(): any {
    return this._fuelSummary;
  }

  /**
   * 📊 Obter análise por fornecedor/posto (cached)
   */
  get supplierAnalysis(): { supplierName: string, totalValue: number, totalLiters: number, count: number }[] {
    return this._supplierAnalysis;
  }

  /**
   * 📊 Obter análise por marca de posto (cached)
   */
  get gasStationAnalysis(): { gasStationName: string, totalValue: number, totalLiters: number, count: number }[] {
    return this._gasStationAnalysis;
  }

  // ========================================
  // 📊 MÉTODOS AUXILIARES (COMPATIBILIDADE)
  // ========================================

  /**
   * 📊 Calcula total de litros (cached)
   */
  getTotalLiters(records: Fuelcontroll[]): number {
    return this._fuelSummary?.totalQuantity || 0;
  }

  /**
   * 📊 Calcula preço médio por litro (cached)
   */
  getAvgPricePerLiter(records: Fuelcontroll[]): number {
    return this._fuelSummary?.avgPricePerLiter || 0;
  }

  /**
   * 🧠 Análise por motorista (formato compatível com template)
   */
  getDriverAnalysisLegacy(records: Fuelcontroll[]): { driverName: string, total: number, count: number, liters: number }[] {
    const drivers = this.analyticsResult?.drivers || [];
    return drivers.map(driver => ({
      driverName: driver.driverName,
      total: driver.totalValue,
      count: driver.totalSupplies,
      liters: driver.totalQuantity
    }));
  }


  /**
   * 📊 Análise de consumo (cached)
   */
  getConsumptionAnalysis(records: Fuelcontroll[]): { avgConsumption: number, bestEfficiency: number, worstEfficiency: number } {
    const consumption = this.analyticsResult?.consumption;
    return {
      avgConsumption: consumption?.avgConsumption || 0,
      bestEfficiency: consumption?.bestEfficiency || 0,
      worstEfficiency: consumption?.worstEfficiency || 0
    };
  }

  // ========================================
  // 🧠 MÉTODOS ADICIONAIS DA NOVA BIBLIOTECA
  // ========================================

  /**
   * 🧠 Obter análise de postos para mapa de calor
   */
  getStationAnalysis(): StationAnalysis[] {
    return this.analyticsResult?.stations || [];
  }

  /**
   * 🧠 Obter dados do mapa de calor
   */
  getHeatMapData() {
    return this.analyticsResult?.heatMap || null;
  }

  /**
   * 🧠 Obter tempo de processamento da análise
   */
  getProcessingTime(): number {
    return this.analyticsResult?.processingTime || 0;
  }

  /**
   * 📊 Processar análise por fornecedor/posto
   */
  private processSupplierAnalysis(data: Fuelcontroll[]): { supplierName: string, totalValue: number, totalLiters: number, count: number }[] {
    const supplierMap = new Map<string, { totalValue: number, totalLiters: number, count: number }>();

    data.forEach(record => {
      // Usar supplierName como nome do fornecedor
      const supplierName = (record as any).supplierName || 'Fornecedor não informado';
      const value = parseFloat(record.value?.toString() || '0');
      
      // Calcular litros totais dos itens
      const totalLiters = (record.items || []).reduce((sum, item) => {
        return sum + parseFloat(item.liters?.toString() || item.quantity?.toString() || '0');
      }, 0);

      if (supplierMap.has(supplierName)) {
        const existing = supplierMap.get(supplierName)!;
        existing.totalValue += value;
        existing.totalLiters += totalLiters;
        existing.count += 1;
      } else {
        supplierMap.set(supplierName, {
          totalValue: value,
          totalLiters: totalLiters,
          count: 1
        });
      }
    });

    // Converter para array e ordenar por valor total (maior primeiro)
    return Array.from(supplierMap.entries())
      .map(([supplierName, data]) => ({
        supplierName,
        ...data
      }))
      .sort((a, b) => b.totalValue - a.totalValue);
  }

  /**
   * 📊 Processar análise por marca de posto
   */
  private processGasStationAnalysis(data: Fuelcontroll[]): { gasStationName: string, totalValue: number, totalLiters: number, count: number }[] {
    const gasStationMap = new Map<string, { totalValue: number, totalLiters: number, count: number }>();

    data.forEach(record => {
      // Usar gasStationBrand como nome da marca do posto
      const gasStationName = record.gasStationBrand || 'Marca não informada';
      const value = parseFloat(record.value?.toString() || '0');
      
      // Calcular litros totais dos itens
      const totalLiters = (record.items || []).reduce((sum, item) => {
        return sum + parseFloat(item.liters?.toString() || item.quantity?.toString() || '0');
      }, 0);

      if (gasStationMap.has(gasStationName)) {
        const existing = gasStationMap.get(gasStationName)!;
        existing.totalValue += value;
        existing.totalLiters += totalLiters;
        existing.count += 1;
      } else {
        gasStationMap.set(gasStationName, {
          totalValue: value,
          totalLiters: totalLiters,
          count: 1
        });
      }
    });

    // Converter para array e ordenar por valor total (maior primeiro)
    return Array.from(gasStationMap.entries())
      .map(([gasStationName, data]) => ({
        gasStationName,
        ...data
      }))
      .sort((a, b) => b.totalValue - a.totalValue);
  }

}
