import { RoutesService } from './../../domain/routes/routes.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Observable, Subject, interval, map, takeUntil, firstValueFrom } from 'rxjs';

import { BaseComponent, PAGE_TITLE } from '../../shared/components/main-layout/base.component';
import { TitleService } from '../../shared/services/theme/title.service';
import { VehiclesService } from '../../domain/vehicles/vehicles.service';
import { DriversService } from '../../domain/drivers/drivers.service';
import { DataTableComponent } from '../../shared/components/data-table/data-table.component';
import { TollparkingService } from '../../domain/tollparking/tollparking.service';
import { DateRangeShortcuts } from '../../shared/utils/date-range.utils';
import { ExpenseChartComponent, ExpenseData, MonthlyComparison } from '../../shared/components/expense-chart/expense-chart.component';
import { ExpenseCardsGridComponent, ExpenseCardConfig } from '../../shared/components/expense-cards-grid/expense-cards-grid.component';
import { RoutesPerformanceDashboardComponent } from '../../shared/components/routes-performance/routes-performance-dashboard.component';
import { VolumesTransportedCardComponent, VolumeData } from '../../shared/components/routes-performance/components/volumes-transported-card.component';
import { FleetTypeCardComponent, FleetTypeData } from '../../shared/components/routes-performance/components/fleet-type-card.component';
import { AccountPayableService } from '../../domain/finances/account-payable/services/accountpayable.service';
import { FuelcontrollService } from '../../domain/fuelcontroll/fuelcontroll.service';
import { FinesService } from '../../domain/fines/fines.service';
import { CompanyService } from '../../domain/company/company.service';

// 📊 Interface para KPIs do Dashboard
interface DashboardKPI {
  label: string;
  value: string;
  change: string;
  trend: 'up' | 'down' | 'stable';
  icon: string;
  color: 'primary' | 'success' | 'warning' | 'info';
  // ✨ NOVOS CAMPOS OPCIONAIS para métricas avançadas
  percentage?: string;      // % em relação ao total
  totalFleetValue?: string; // Valor total discreto
  efficiency?: string;      // Eficiência da frota
  subtitle?: string;        // Informação adicional
}

// 📈 Interface para dados de gráfico
interface ChartData {
  labels: string[];
  values: number[];
}

export interface RawFilters {
  [key: string]: any;
}


@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [CommonModule, DataTableComponent, ExpenseCardsGridComponent, RoutesPerformanceDashboardComponent, VolumesTransportedCardComponent, FleetTypeCardComponent],
  providers: [
    { provide: PAGE_TITLE, useValue: 'Dashboard - PraFrota' }
  ],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.scss'
})
export class DashboardComponent extends BaseComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();
  
  // 📊 Dados dos KPIs
  kpis: DashboardKPI[] = [];
  
  filters: RawFilters = {};
  
  // 📈 Dados dos gráficos
  efficiencyChart: ChartData = { labels: [], values: [] };
  economyChart: ChartData = { labels: [], values: [] };
  
  // 🚛 Dados da tabela de veículos
  vehiclesTableConfig: any = {};
  recentVehicles: any[] = [];
  
  // ⏱️ Dados em tempo real
  lastUpdate: string = '';
  isLoading = true;
  
  // 📊 Dados do gráfico de despesas
  expenseData: ExpenseData[] = [];
  paymentAdvanceData: ExpenseData[] = [];
  fuelData: ExpenseData[] = [];
  finesData: ExpenseData[] = [];

  // ✨ NOVOS: Dados do mês anterior para comparação
  previousMonthExpenseData: ExpenseData[] = [];
  previousMonthPaymentAdvanceData: ExpenseData[] = [];
  previousMonthFuelData: ExpenseData[] = [];
  previousMonthFinesData: ExpenseData[] = [];
  
  // 🏢 Dados de breakdown por empresa
  companyBreakdown: {
    name: string;
    totalValue: number;
    totalCount: number;
    expenses: { type: string; value: number; count: number; }[];
  }[] = [];

  // 🚛 Dados de volumes transportados
  volumeData: VolumeData = {
    totalVolumes: 0,
    averagePerVehicle: 0,
    efficiency: 0,
    concluded: 0,
    active: 0,
    pending: 0,
    delayed: 0,
    changePercentage: 0,
    trend: 'stable',
    priority: 0,
    hasAmbulance: 0
  };

  // 🚛 Dados de tipo de frota
  fleetTypeData: FleetTypeData = {
    totalRoutes: 0,
    totalVolumes: 0,
    totalDistance: 0,
    changePercentage: 0,
    trend: 'stable',
    hasAmbulance: 0,
    fleetTypes: {
      rental: { label: 'Rentals', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
      corporate: { label: 'Corporativo', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
      aggregate: { label: 'Agregado', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
      fixedRental: { label: 'Frota Fixa - Locação', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
      fixedDaily: { label: 'Frota Fixa - Diarista', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
      other: { label: 'Outros', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 }
    }
  };
  

  // 📊 Configuração dos Cards de Despesas
  expenseCards: ExpenseCardConfig[] = [
    {
      id: 'tollparking',
      title: 'Pedágio e estacionamento',
      data: [],
      config: {
        title: 'Pedágio e estacionamento',
        showPercentages: true,
        showCounts: true,
        animated: true,
        // height: '550px',
        groupByCompany: false,
        showCompanyFilter: false
      },
      enabled: true,
      order: 1,
      // description: 'Despesas com pedágios e estacionamentos do mês atual'
    },
    {
      id: 'fuel',
      title: 'Controle de Combustível',
      data: [],
      config: {
        title: 'Controle de Combustível',
        showPercentages: true ,
        showCounts: true ,
        animated: true ,
        // height: '550px' ,
        groupByCompany: false ,
        showCompanyFilter: false
      },
      enabled: true, // Desabilitado por padrão - pode ser habilitado conforme necessário
      order: 2,
      // description: 'Análise de consumo e custos de combustível'
    },    
    {
      id: 'fines',
      title: 'Multas',
      data: [],
      config: {
        title: 'Multas',
        showPercentages: true ,
        showCounts: true ,
        animated: true ,
        // height: '550px' ,
        groupByCompany: false ,
        showCompanyFilter: false
      },
      enabled: true, // Desabilitado por padrão - pode ser habilitado conforme necessário
      order: 2,
      // description: 'Análise de consumo e custos de combustível'
    },
    {
      id: 'payments',
      title: 'Status de Pagamentos e Antecipações',
      data: [],
      config: {
        title: 'Status de Pagamentos e Antecipações',
        showPercentages: true,
        showCounts: true,
        animated: true,
        // height: '550px',
        groupByCompany: false,
        showCompanyFilter: false
      },
      enabled: true,
      order: 3,
      // description: 'Controle de pagamentos aprovados e antecipações'
    },
    
  ];

  constructor(
    titleService: TitleService ,
    private vehiclesService    : VehiclesService ,
    private driversService     : DriversService ,
    private tollParkingService : TollparkingService ,
    private fuelService           : FuelcontrollService ,
    private accountPayableService : AccountPayableService ,
    private finesService: FinesService ,
    private companyService: CompanyService ,
    private routesService: RoutesService
  ) {
    super(titleService, 'Dashboard - PraFrota');
  }

  override ngOnInit() {
    this.initializeDashboard();
    this.startRealTimeUpdates();
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  // 🚀 Inicializar dashboard
  private async initializeDashboard() {
    this.isLoading = true;
    
    try {
      // Carregar dados em paralelo
      await Promise.all([
        this.loadKPIs(),
        this.loadChartData(),
        // this.loadVehiclesTable(),
        // Dados de rotas
        this.loadRoutes(),
        this.loadFleetTypes(),
        // Dados do mês atual
        this.loadKPIsExpenseTollParkingData(),
        this.loadKPIsExpensePaymentAndAdvanceData(),
        this.loadKPIsExpenseFuelData(),        
        this.loadKPIsExpenseFinesData(),
        // ✨ NOVOS: Dados do mês anterior
        this.loadPreviousMonthTollParkingData(),
        this.loadPreviousMonthPaymentAndAdvanceData(),
        this.loadPreviousMonthFuelData(),
        this.loadPreviousMonthFinesData()
      ]);
      
      this.lastUpdate = new Date().toLocaleTimeString('pt-BR');
      this.isLoading = false;
    } catch (error) {
      console.error('Erro ao carregar dashboard:', error);
      this.isLoading = false;
    }
  }

  private async loadCompanyOptions(): Promise<void> {
    return new Promise((resolve) => {
      this.companyService.getCompanies(1, 100000).subscribe({
        next: (response) => {
          const allCompanyIds = response.data.map((company: any) => company.id);
          this.filters['companyIds'] = allCompanyIds;
          resolve();
        },
        error: (error) => {
          console.warn('⚠️ Erro ao carregar empresas, usando dados de fallback', error);
          this.filters['companyIds'] = [];
          resolve();
        }
      });
    });
  }
  // priority
  private async loadRoutes() {
    try {
      const today = DateRangeShortcuts.today();
      const filtersRoutes = {
        start_date: today.date_start,
        end_date: today.date_end,
        status: ['PENDING', 'INPROGRESS', 'DELIVERED', 'DELAYED', 'CANCELLED']
      };

      const todayYestDay = DateRangeShortcuts.yesterday();
      const filtersRoutesYestDay = {
        start_date: todayYestDay.date_start,
        end_date: todayYestDay.date_end,
        status: ['PENDING', 'INPROGRESS', 'DELIVERED', 'DELAYED', 'CANCELLED']
      };

      const statusRoutes = await firstValueFrom(this.routesService.getRoutes(1, 100000, filtersRoutes as any));
      const statusRoutesYestDay = await firstValueFrom(this.routesService.getRoutes(1, 100000, filtersRoutesYestDay as any));

      if (statusRoutes?.data) {
        // Processar dados das rotas
        const routes = statusRoutes.data;
        const routesYestDay = statusRoutesYestDay.data;
        const totalVolumes = routes.reduce((sum: number, r: any) => sum + (r.volume || 0), 0);
        const totalVolumesYestDay = routesYestDay.reduce((sum: number, r: any) => sum + (r.volume || 0), 0);
        const priority = routes.reduce((sum: number, r: any) => sum + (r.priority === 'high' || r.priority === 'urgent' || r.priority === 'HIGH' || r.priority === 'URGENT' ? 1 :  0), 0);
        const hasAmbulance = routes.reduce((sum: number, r: any) => sum + (r.hasAmbulance === true ? 1 :  0), 0);

        // Contar por status
        const concluded = routes.filter((r: any) => r.status === 'DELIVERED').length;
        const active    = routes.filter((r: any) => r.status === 'INPROGRESS').length;
        const pending   = routes.filter((r: any) => r.status === 'PENDING').length;
        const delayed   = routes.filter((r: any) => r.status === 'DELAYED').length;

        // ✨ NOVO: Contar por status E tipo de rota
        const concludedByType = {
          firstMile: routes.filter((r: any) => r.status === 'DELIVERED' && (r.type === 'firstMile' || r.type === 'FIRSTMILE')).length,
          lineHaul: routes.filter((r: any) => r.status === 'DELIVERED' && (r.type === 'lineHaul' || r.type === 'LINEHAUL')).length,
          lastMile: routes.filter((r: any) => r.status === 'DELIVERED' && (r.type === 'lastMile' || r.type === 'LASTMILE')).length,
          custom: routes.filter((r: any) => r.status === 'DELIVERED' && r.type === 'custom').length
        };

        const activeByType = {
          firstMile: routes.filter((r: any) => r.status === 'INPROGRESS' && (r.type === 'firstMile' || r.type === 'FIRSTMILE')).length,
          lineHaul: routes.filter((r: any) => r.status === 'INPROGRESS' && (r.type === 'lineHaul' || r.type === 'LINEHAUL')).length,
          lastMile: routes.filter((r: any) => r.status === 'INPROGRESS' && (r.type === 'lastMile' || r.type === 'LASTMILE')).length,
          custom: routes.filter((r: any) => r.status === 'INPROGRESS' && r.type === 'custom').length
        };

        const pendingByType = {
          firstMile: routes.filter((r: any) => r.status === 'PENDING' && (r.type === 'firstMile' || r.type === 'FIRSTMILE')).length,
          lineHaul: routes.filter((r: any) => r.status === 'PENDING' && (r.type === 'lineHaul' || r.type === 'LINEHAUL')).length,
          lastMile: routes.filter((r: any) => r.status === 'PENDING' && (r.type === 'lastMile' || r.type === 'LASTMILE')).length,
          custom: routes.filter((r: any) => r.status === 'PENDING' && r.type === 'custom').length
        };

        const delayedByType = {
          firstMile: routes.filter((r: any) => r.status === 'DELAYED' && (r.type === 'firstMile' || r.type === 'FIRSTMILE')).length,
          lineHaul: routes.filter((r: any) => r.status === 'DELAYED' && (r.type === 'lineHaul' || r.type === 'LINEHAUL')).length,
          lastMile: routes.filter((r: any) => r.status === 'DELAYED' && (r.type === 'lastMile' || r.type === 'LASTMILE')).length,
          custom: routes.filter((r: any) => r.status === 'DELAYED' && r.type === 'custom').length
        };

        // Calcular métricas
        const totalVehicles = routes.length;
        const averagePerVehicle = totalVehicles > 0 ? totalVolumes / totalVehicles : 0;
        const efficiency = totalVolumes > 0 ? (concluded / totalVehicles) * 100 : 0;
        
        // ✨ NOVO: Calcular rotas com prioridade (high, urgent)
        const priorityRoutes = routes.filter((r: any) => 
          r.priority === 'high' || r.priority === 'urgent' || r.priority === 'HIGH' || r.priority === 'URGENT'
        ).length;

        // Calcular trend (comparação com período anterior - simulado)
        const changePercentage = (totalVolumes - totalVolumesYestDay) / totalVolumesYestDay * 100; // Valor da imagem
        const trend: 'up' | 'down' | 'stable' = changePercentage > 0 ? 'up' : changePercentage < 0 ? 'down' : 'stable';

        // Atualizar dados do volume
        this.volumeData = {
          totalVolumes ,
          averagePerVehicle ,
          efficiency ,
          concluded ,
          active ,
          pending ,
          delayed ,
          changePercentage ,
          trend,
          // ✨ NOVO: Incluir breakdown por tipo
          concludedByType,
          activeByType,
          pendingByType,
          delayedByType,
          priority,
          hasAmbulance  
        };

        console.log('📊 Volume Data processado:', this.volumeData);
        console.log('🔍 DEBUG - Dados de rotas:', {
          totalRoutes: routes.length,
          routesWithType: routes.filter((r: any) => r.type).length,
          typesFound: [...new Set(routes.map((r: any) => r.type))],
          statusFound: [...new Set(routes.map((r: any) => r.status))],
          sampleRoutes: routes.slice(0, 3).map((r: any) => ({ id: r.id, type: r.type, status: r.status })),
          concludedByType,
          totalConcluded: concluded
        });
      }
    } catch (error) {
      console.error('Erro ao carregar dados de rotas:', error);
    
    }
  }

  // 🚛 Carregar dados de tipo de frota
  private async loadFleetTypes() {
    try {
      const today = DateRangeShortcuts.today();
      const filtersRoutes = {
        start_date: today.date_start,
        end_date: today.date_end,
        status: ['PENDING', 'INPROGRESS', 'DELIVERED', 'DELAYED', 'CANCELLED']
      };

      const todayYestDay = DateRangeShortcuts.yesterday();
      const filtersRoutesYestDay = {
        start_date: todayYestDay.date_start,
        end_date: todayYestDay.date_end,
        status: ['PENDING', 'INPROGRESS', 'DELIVERED', 'DELAYED', 'CANCELLED']
      };

      const statusRoutes = await firstValueFrom(this.routesService.getRoutes(1, 100000, filtersRoutes as any));
      const statusRoutesYestDay = await firstValueFrom(this.routesService.getRoutes(1, 100000, filtersRoutesYestDay as any));

      if (statusRoutes?.data) {
        const routes = statusRoutes.data;
        const routesYestDay = statusRoutesYestDay.data;
        
        // Calcular totais
        const totalRoutes = routes.length;
        const totalRoutesYestDay = routesYestDay.length;
        const totalVolumes = routes.reduce((sum: number, r: any) => sum + (r.volume || 0), 0);
        const totalVolumesYestDay = routesYestDay.reduce((sum: number, r: any) => sum + (r.volume || 0), 0);
        const totalDistance = routes.reduce((sum: number, r: any) => sum + (r.totalDistance || 0), 0);
        const hasAmbulance = routes.reduce((sum: number, r: any) => sum + (r.hasAmbulance === true ? 1 : 0), 0);

        // Mapear tipos de frota do backend para nossa interface
        const fleetTypeMapping: { [key: string]: keyof FleetTypeData['fleetTypes'] } = {
          'RENTAL': 'rental',
          'CORPORATE': 'corporate', 
          'AGGREGATE': 'aggregate',
          'FIXED_RENTAL': 'fixedRental',
          'FIXED_DAILY': 'fixedDaily',
          'OTHER': 'other'
        };

        // Inicializar dados dos tipos de frota
        const fleetTypesData: FleetTypeData['fleetTypes'] = {
          rental: { label: 'Rentals', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
          corporate: { label: 'Corporativo', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
          aggregate: { label: 'Agregado', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
          fixedRental: { label: 'Frota Fixa - Locação', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
          fixedDaily: { label: 'Frota Fixa - Diarista', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 },
          other: { label: 'Outros', routes: 0, volumes: 0, distance: 0, percentage: 0, hasAmbulance: 0 }
        };

        // Processar cada rota e agrupar por tipo de frota
        routes.forEach((route: any) => {
          const fleetType = route.vehicleFleetType || 'OTHER';
          const mappedType = fleetTypeMapping[fleetType] || 'other';
          
          fleetTypesData[mappedType].routes += 1;
          fleetTypesData[mappedType].volumes += (route.volume || 0);
          fleetTypesData[mappedType].distance += (route.totalDistance || 0);
          if (route.hasAmbulance === true) {
            fleetTypesData[mappedType].hasAmbulance += 1;
          }
        });

        // Calcular percentuais
        Object.keys(fleetTypesData).forEach(key => {
          const typedKey = key as keyof FleetTypeData['fleetTypes'];
          if (totalRoutes > 0) {
            fleetTypesData[typedKey].percentage = (fleetTypesData[typedKey].routes / totalRoutes) * 100;
          }
        });

        // Calcular trend (comparação com período anterior)
        const changePercentage = totalRoutesYestDay > 0 
          ? ((totalRoutes - totalRoutesYestDay) / totalRoutesYestDay) * 100 
          : 0;
        const trend: 'up' | 'down' | 'stable' = changePercentage > 0 ? 'up' : changePercentage < 0 ? 'down' : 'stable';

        // Atualizar dados do tipo de frota
        this.fleetTypeData = {
          totalRoutes,
          totalVolumes,
          totalDistance,
          changePercentage,
          trend,
          hasAmbulance,
          fleetTypes: fleetTypesData
        };

        console.log('🚛 Fleet Type Data processado:', this.fleetTypeData);
        console.log('🔍 DEBUG - Breakdown por tipo de frota:', {
          totalRoutes,
          totalDistance,
          fleetTypesFound: [...new Set(routes.map((r: any) => r.vehicleFleetType))],
          sampleRoutes: routes.slice(0, 5).map((r: any) => ({ 
            id: r.id, 
            vehicleFleetType: r.vehicleFleetType, 
            volume: r.volume,
            totalDistance: r.totalDistance,
            hasAmbulance: r.hasAmbulance 
          })),
          fleetTypesData
        });
      }
    } catch (error) {
      console.error('Erro ao carregar dados de tipo de frota:', error);
    }
  }

  /**
   * 🚛 Obter total de veículos para cálculo da média
   */
  private async getTotalVehicles(): Promise<number> {
    try {
      const vehiclesResponse = await firstValueFrom(this.vehiclesService.getVehicles(1, 1));
      return vehiclesResponse?.totalCount || 0;
    } catch (error) {
      console.error('Erro ao obter total de veículos:', error);
      return 0;
    }
  }

  // 📊 Carregar KPIs principais
  private async loadKPIs() {
    
    // 📊 Carregar opções de empresa (aguardar conclusão)
    await this.loadCompanyOptions();

    // 🚛 Carregar dados de veículos
    // Buscar dados reais dos services
    const vehiclesResponse = await firstValueFrom(this.vehiclesService.getVehicles(1, 100000, this.filters));
    vehiclesResponse.data = vehiclesResponse.data.filter((v: any) => v.fleetType !== 'AGGREGATE');
    const totalVehicles    = vehiclesResponse?.data?.length || 0;
    const totalValue       = vehiclesResponse?.data?.reduce((sum, v) => sum + (v.price || 0), 0) || 0;
    
 

    // 🚛 Carregar dados de veículos em uso
    const statusInUse = vehiclesResponse.data.filter((v: any) => v.status === 'in_use' && v.fleetType !== 'AGGREGATE');
    const totalVehiclesInUseQtd = statusInUse.length;
    const totalVehiclesInUseValue = statusInUse.reduce((sum: number, v: any) => sum + (v.price || 0), 0) || 0;

    const efficiency = totalVehicles > 0 ? Math.round((totalVehiclesInUseQtd / totalVehicles) * 100) : 0;
    const valuePercentage = totalValue > 0 ? ((totalVehiclesInUseValue / totalValue) * 100).toFixed(1) : '0.0';
    
    // 🎯 DETERMINAR TREND baseado no percentual de utilização
    const getVehicleUsageTrend = (percentage: number): 'up' | 'down' | 'stable' => {
      if (percentage > 90) return 'up';
      if (percentage >= 80 && percentage <= 90) return 'stable';
      return 'down'; // percentage < 80
    };
    const vehicleUsageTrend = getVehicleUsageTrend(parseFloat(valuePercentage));
    
    // 🚛 Carregar dados de veículos a venda
    const vehiclesSalesResponse = vehiclesResponse.data.filter((v: any) => v.status === 'for_sale'  && v.fleetType !== 'AGGREGATE');
    const totalVehiclesSalesQtd = vehiclesSalesResponse.length;
    const totalVehiclesSalesValue = (vehiclesSalesResponse as any)?.reduce((sum: number, v: any) => sum + (v.price_sale || 0), 0) || 0;
    
    // 📊 MÉTRICAS AVANÇADAS: Percentual de veículos à venda em relação ao total
    const salesEfficiency = totalVehicles > 0 ? Math.round((totalVehiclesSalesQtd / totalVehicles) * 100) : 0;
    const salesValuePercentage = totalValue > 0 ? ((totalVehiclesSalesValue / totalValue) * 100).toFixed(1) : '0.0';
    
    // 🎯 DETERMINAR TREND baseado no percentual de veículos à venda
    const getVehiclesSalesTrend = (percentage: number): 'up' | 'down' | 'stable' => {
      if (percentage > 2) return 'up';      // Muitos veículos à venda (pode ser bom para vendas)
      if (percentage >= 1 && percentage <= 2) return 'stable'; // Quantidade normal
      return 'down'; // Poucos veículos à venda (pode precisar de mais estoque)
    };
    const vehiclesSalesTrend = getVehiclesSalesTrend(parseFloat(salesValuePercentage));
  
     
    // 🚛 Carregar dados de veículos alugados
    const vehiclesRentedResponse = vehiclesResponse.data.filter((v: any) => v.status === 'rented' && v.fleetType !== 'AGGREGATE');
    const totalVehiclesRentedQtd = vehiclesRentedResponse.length;
    const totalVehiclesRentedValue = vehiclesRentedResponse.reduce((sum: number, v: any) => sum + (v.price || 0), 0) || 0;
    
    // 📊 MÉTRICAS AVANÇADAS: Percentual de veículos alugados em relação ao total
    const rentedEfficiency = totalVehicles > 0 ? Math.round((totalVehiclesRentedQtd / totalVehicles) * 100) : 0;
    const rentedValuePercentage = totalValue > 0 ? ((totalVehiclesRentedValue / totalValue) * 100).toFixed(1) : '0.0';
    
    // 🎯 DETERMINAR TREND baseado no percentual de veículos alugados
    const getVehiclesRentedTrend = (percentage: number): 'up' | 'down' | 'stable' => {
      if (percentage > 10) return 'stable';      // Alta taxa de locação (bom para receita)
      if (percentage >= 3 && percentage <= 10) return 'stable'; // Taxa normal de locação
      return 'stable'; // Baixa taxa de locação (pode melhorar)
    };
    const vehiclesRentedTrend = getVehiclesRentedTrend(parseFloat(rentedValuePercentage));

    
    // 🚛 Carregar dados de veículos em manutenção
    const vehiclesMaintenanceResponse = vehiclesResponse.data.filter((v: any) => v.status === 'under_maintenance' || v.status === 'under_review'  && v.fleetType !== 'AGGREGATE');  
    const totalVehiclesMaintenanceQtd = vehiclesMaintenanceResponse.length;
    const totalVehiclesMaintenanceValue = (vehiclesMaintenanceResponse as any)?.reduce((sum: number, v: any) => sum + (v.price || 0), 0) || 0;
    
    // 📊 MÉTRICAS AVANÇADAS: Percentual de veículos em manutenção em relação ao total
    const maintenanceEfficiency = totalVehicles > 0 ? Math.round((totalVehiclesMaintenanceQtd / totalVehicles) * 100) : 0;
    const maintenanceValuePercentage = totalValue > 0 ? ((totalVehiclesMaintenanceValue / totalValue) * 100).toFixed(1) : '0.0';
    
    // 🎯 DETERMINAR TREND baseado no percentual de veículos em manutenção
    const getVehiclesMaintenanceTrend = (percentage: number): 'up' | 'down' | 'stable' => {
      if (percentage > 5) return 'up';    // Muitos veículos em manutenção (problemático)
      if (percentage >= 3 && percentage <= 5) return 'stable'; // Taxa normal de manutenção
      return 'down'; // Poucos veículos em manutenção (bom para operação)
    };
    const vehiclesMaintenanceTrend = getVehiclesMaintenanceTrend(parseFloat(maintenanceValuePercentage));

    const driversResponse = await firstValueFrom(this.driversService.getDrivers(1, 100));
    const totalDrivers = driversResponse?.totalCount || 0;

      

    // ✅ Usando utility para período do mês atual
    const dateFilters = DateRangeShortcuts.currentMonth();
    
    const tollParkingResponse = await firstValueFrom(this.tollParkingService.getTollparkings(1, 10000, dateFilters));
    
    // const totalTollParkingValue = tollParkingResponse?.data?.reduce((sum, v) => sum + (v.value || 0), 0) || 0;
    // const totalTollParkingQtd = tollParkingResponse?.totalCount || 0;

    const vehiclesFinanceResponse = await firstValueFrom(this.vehiclesService.getVehicles(1, 10000, {"paymentInstallmentsOpen": "true"}));

    const vehiclesFinanceResponseData = vehiclesFinanceResponse.data.filter((v: any) =>v.fleetType !== 'AGGREGATE');
    const vehiclesFinanceResponseQtd = vehiclesFinanceResponseData.length || 0;
    const vehiclesFinanceResponseValue = (vehiclesFinanceResponseData as any)?.reduce((sum: number, v: any) => sum + (v.price || 0), 0) || 0;
    
    // 📊 MÉTRICAS AVANÇADAS: Percentual de veículos financiados em relação ao total
    const financeEfficiency = totalVehicles > 0 ? Math.round((vehiclesFinanceResponseQtd / totalVehicles) * 100) : 0;
    const financeValuePercentage = totalValue > 0 ? ((vehiclesFinanceResponseValue / totalValue) * 100).toFixed(1) : '0.0';
    
    // 🎯 DETERMINAR TREND baseado no percentual de saldo de financiamento
    const getFinanceBalanceTrend = (percentage: number): 'up' | 'down' | 'stable' => {
      if (percentage > 30) return 'up';    // Alto endividamento (pode ser problemático)
      if (percentage >= 20 && percentage <= 30) return 'stable'; // Endividamento normal
      return 'down'; // Baixo endividamento (boa situação financeira)
    };
    const financeBalanceTrend = getFinanceBalanceTrend(parseFloat(financeValuePercentage));
    

    this.kpis = [
      {
        label: 'Veículos em uso',
        value: this.formatCurrency(totalVehiclesInUseValue),
        change: `${valuePercentage}%`,
        trend: vehicleUsageTrend, // 🎯 TREND DINÂMICO baseado no percentual
        icon: 'fas fa-car-side',
        color: 'primary',
        // ✨ NOVAS MÉTRICAS
        percentage: `${valuePercentage}%`,
        totalFleetValue: this.formatCurrency(totalValue),
        efficiency: `${efficiency}%`,
        subtitle: `${totalVehiclesInUseQtd} de ${totalVehicles} veículos -Total R$ ${this.formatCurrency(totalValue)}`
      },
      {
        label: 'Veículos a venda',
        value: this.formatCurrency(totalVehiclesSalesValue),
        change: `${salesValuePercentage}%`,
        trend: vehiclesSalesTrend, // 🎯 TREND DINÂMICO baseado no percentual
        icon: 'fas fa-truck',
        color: 'success',
        // ✨ NOVAS MÉTRICAS
        percentage: `${salesValuePercentage}%`,
        totalFleetValue: this.formatCurrency(totalValue),
        efficiency: `${salesEfficiency}%`,
        subtitle: `${totalVehiclesSalesQtd} de ${totalVehicles} veículos - Total ${this.formatCurrency(totalValue)}`
      },
      {
        label: 'Veículos alugados',
        value: this.formatCurrency(totalVehiclesRentedValue),
        change: `${rentedValuePercentage}%`,
        trend: vehiclesRentedTrend, // 🎯 TREND DINÂMICO baseado no percentual
        icon: 'fas fa-car-side',
        color: 'success',
        // ✨ NOVAS MÉTRICAS
        percentage: `${rentedValuePercentage}%`,
        totalFleetValue: this.formatCurrency(totalValue),
        efficiency: `${rentedEfficiency}%`,
        subtitle: `${totalVehiclesRentedQtd} de ${totalVehicles} veículos - Total ${this.formatCurrency(totalValue)}`
      },           
      {
        label: 'Veículos em manutenção',
        value: this.formatCurrency(totalVehiclesMaintenanceValue),
        change: `${maintenanceValuePercentage}%`,
        trend: vehiclesMaintenanceTrend, // 🎯 TREND DINÂMICO baseado no percentual
        icon: 'fas fa-car-crash',
        color: 'warning',
        // ✨ NOVAS MÉTRICAS
        percentage: `${maintenanceValuePercentage}%`,
        totalFleetValue: this.formatCurrency(totalValue),
        efficiency: `${maintenanceEfficiency}%`,
        subtitle: `${totalVehiclesMaintenanceQtd} de ${totalVehicles} veículos - Total ${this.formatCurrency(totalValue)}`
      },
      {
        label: 'Veículos Financiados/Garantia',
        value: this.formatCurrency(vehiclesFinanceResponseValue),
        change: `${financeValuePercentage}%`,
        trend: financeBalanceTrend, // 🎯 TREND DINÂMICO baseado no percentual
        icon: 'fas fa-dollar-sign',
        color: 'warning',
        // ✨ NOVAS MÉTRICAS
        percentage: `${financeValuePercentage}%`,
        totalFleetValue: this.formatCurrency(totalValue),
        efficiency: `${financeEfficiency}%`,
        subtitle: `${vehiclesFinanceResponseQtd} de ${totalVehicles} veículos - Total ${this.formatCurrency(totalValue)}`
      },
      
      // {
      //   label: 'Pedágios e estacionamentos',
      //   value: this.formatCurrency(totalTollParkingValue),
      //   change: '',
      //   trend: 'stable',
      //   icon: 'fas fa-users',
      //   color: 'info'
      // }
      // {
      //   label: 'Eficiência',
      //   value: `${efficiency}%`,
      //   change: '+2.1%',
      //   trend: 'up',
      //   icon: 'fas fa-chart-line',
      //   color: 'success'
      // },

     
      // {
      //   label: 'Economia Mensal',
      //   value: `R$ ${(savedAmount / 1000).toFixed(1)}K`,
      //   change: '+8.5%',
      //   trend: 'up',
      //   icon: 'fas fa-piggy-bank',
      //   color: 'warning'
      // },
      // {
      //   label: 'Motoristas Ativos',
      //   value: totalDrivers.toString(),
      //   change: '+1.8%',
      //   trend: 'up',
      //   icon: 'fas fa-users',
      //   color: 'info'
      // }
    ];
  }

  // 📈 Carregar dados dos gráficos
  private async loadChartData() {
    // Dados simulados para os gráficos (em produção, viriam do backend)
    this.efficiencyChart = {
      labels: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul'],
      values: [85, 87, 90, 88, 92, 95, 98]
    };
    
    this.economyChart = {
      labels: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul'],
      values: [12.5, 13.2, 14.8, 13.9, 15.2, 16.1, 15.7]
    };
  }

  // 🚛 Carregar tabela de veículos recentes
  private async loadVehiclesTable() {
    const response = await firstValueFrom(this.vehiclesService.getVehicles(1, 5));
    this.recentVehicles = response?.data || [];
    
    // Configuração da tabela (usando nosso sistema existente)
    this.vehiclesTableConfig = {
      columns: [
        { field: "license_plate", header: "Placa", sortable: true },
        { field: "brand", header: "Marca", sortable: true },
        { field: "model", header: "Modelo", sortable: true },
        { 
          field: "status", 
          header: "Status", 
          label: (value: any) => {
            const statusMap: { [key: string]: string } = {
              'Ativo': '🟢 Ativo',
              'Inativo': '🔴 Inativo',
              'Manutenção': '🟡 Manutenção'
            };
            return statusMap[value] || value;
          }
        },
        { 
          field: "price", 
          header: "Valor", 
          label: (value: any) => {
            if (!value) return '-';
            return `R$ ${Number(value).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;
          },
          footer: {
            type: 'sum',
            format: 'currency',
            label: 'Total:'
          }
        }
      ],
      actions: [
        {
          icon: 'fas fa-eye',
          label: 'Visualizar',
          action: 'view',
          color: 'primary'
        }
      ]
    };
  }

  // ⏱️ Iniciar atualizações em tempo real
  private startRealTimeUpdates() {
    // Atualizar dados a cada 30 segundos
    interval(60000)
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {
        this.refreshData();
      });
  }

  private async loadKPIsExpenseFinesData() {
    try {
      const dateFilters = DateRangeShortcuts.currentMonth();
      const finesResponse = await firstValueFrom(
        this.finesService.getVehicleFinesDashboardList(1, 100000, {start_due_date: dateFilters.date_start, end_due_date: dateFilters.date_end} )
      );
      
      
      const expenseMap = new Map<string, { fineValue: number; totalFine: number }>();
      
      // Inicializar todos os tipos - severity
      const types: ('GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE')[] = ['GRAVISSIMA', 'GRAVE', 'MÉDIA', 'LEVE'];
      types.forEach(type => {
        expenseMap.set(type, { fineValue: 0, totalFine: 0 });
      });

      // Processar dados reais
      if (finesResponse?.data) {
        // ✅ Filtrar registros com valor negativo
        const filteredData = finesResponse.data.filter(item => {
          const itemValue = Number(item.fine_value) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredData.forEach(item => {
          // Determinar o tipo baseado no campo severity com mapeamento completo
          let type: 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE' = 'LEVE';
          
          if (item.severity) {
            type = this.mapSeverityToType(item.severity) as 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE';
          }
          
          const current = expenseMap.get(type) || { fineValue: 0, totalFine: 0 };
          const itemValue = Number(item.fine_value) || 0;
          
          expenseMap.set(type, {
            fineValue: current.fineValue + itemValue,
            totalFine: current.totalFine + 1
          });
        });
      }
      
      // Converter para array de ExpenseData
      this.finesData = Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE',
          value: data.fineValue,
          count: data.totalFine
        }))
        .filter(item => item.value > 0 || item.count > 0); // Mostrar apenas tipos com dados
      
      // 📊 Atualizar dados dos cards
      this.updateExpenseCards();
      
    } catch (error) {
      console.error('Erro ao carregar dados de multas:', error);
      this.finesData = [];
      this.updateExpenseCards(); 
    }
    
  }
  // 📊 Carregar dados do gráfico de despesas
  private async loadKPIsExpenseFuelData() {
    try {
      // ✅ Usando utility para período do mês atual
      // const dateFilters = DateRangeShortcuts.last30Days();
      const dateFilters = DateRangeShortcuts.currentMonth();
      
      const fuelResponse = await firstValueFrom(
        this.fuelService.getFuelcontrollsDashboardList(1, 100000, {start_date: dateFilters.date_start, end_date: dateFilters.date_end} )        
      );

      // Agrupar dados por tipo
      const expenseMap = new Map<string, { totalValue: number; totalSupplies: number }>();
      
      // Inicializar todos os tipos
      const types: ('Fuel' | 'Others')[] = ['Fuel', 'Others'];
      types.forEach(type => {
        expenseMap.set(type, { totalValue: 0, totalSupplies: 0 });
      });
      
      // Processar dados reais
      if (fuelResponse?.data) {
        // ✅ Filtrar registros com valor negativo
        const filteredData = fuelResponse.data.filter(item => {
          const itemValue = Number(item.totalValue) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredData.forEach(item => {
          // Determinar o tipo baseado no campo type ou inferir de outros campos
          let type: 'Fuel' | 'Others' = 'Others';
          
          if (item.type && (item.type === 'Fuel' || item.type === 'Others')) {
            type = item.type;
          }
          
          const current = expenseMap.get(type) || { totalValue: 0, totalSupplies: 0 };
          const itemValue = Number(item.totalValue) || 0;
          
          expenseMap.set(type, {
            totalValue: current.totalValue + itemValue,
            totalSupplies: current.totalSupplies + 1
          });
        });
      }
      
      // Converter para array de ExpenseData com dados individuais (incluindo companyName)
      const expenseDataWithCompanies: ExpenseData[] = [];
      
      if (fuelResponse?.data) {
        // ✅ Aplicar o mesmo filtro para dados com companyName
        const filteredDataForCompanies = fuelResponse.data.filter(item => {
          const itemValue = Number(item.value) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredDataForCompanies.forEach(item => {
          // Determinar o tipo (mesmo lógica de antes)
          let type: 'Fuel' | 'Others' = 'Others';
          
          if (item.type && (item.type === 'Fuel' || item.type === 'Others')) {
            type = item.type;
          }
          
          expenseDataWithCompanies.push({
            type,
            value: Number(item.totalValue) || 0,
            count: Number(item.totalSupplies) || 0, // Cada item conta como 1
            companyName: item.companyName || 'Empresa Não Informada'
          });
        });
      }
      
      // Para compatibilidade, manter também os dados agregados
      this.fuelData = expenseDataWithCompanies.length > 0 ? expenseDataWithCompanies : Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'Fuel' | 'Others',
          value: data.totalValue,
          count: data.totalSupplies
        }))
        .filter(item => item.value > 0 || item.count > 0);
        

      
      // 🏢 Processar breakdown por empresa
      this.processCompanyBreakdown();
      
      // 📊 Atualizar dados dos cards
      this.updateExpenseCards();
        
    } catch (error) {
      console.error('Erro ao carregar dados de despesas:', error);
      this.expenseData = [];
      this.updateExpenseCards();
    }
  }

  // 📊 Carregar dados do gráfico de despesas
  private async loadKPIsExpenseTollParkingData() {
    try {
      const today = DateRangeShortcuts.today();
      // ✅ Usando utility para período do mês atual
      const dateFilters = DateRangeShortcuts.currentMonth();
     
      const tollParkingResponse = await firstValueFrom(
        this.tollParkingService.getTollparkingsDashboardList(1, 10000, dateFilters)                      
      );
      
      // Agrupar dados por tipo
      const expenseMap = new Map<string, { value: number; count: number }>();
      
      // Inicializar todos os tipos
      const types: ('Toll' | 'Parking' | 'Signature' | 'Others')[] = ['Toll', 'Parking', 'Signature', 'Others'];
      types.forEach(type => {
        expenseMap.set(type, { value: 0, count: 0 });
      });
      
      // Processar dados reais
      if (tollParkingResponse?.data) {
        // ✅ Filtrar registros com valor negativo
        const filteredData = tollParkingResponse.data.filter(item => {
          const itemValue = Number(item.value) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredData.forEach(item => {
          // Determinar o tipo baseado no campo type ou inferir de outros campos
          let type: 'Toll' | 'Parking' | 'Signature' | 'Others' = 'Others';
          
          if (item.type) {
            type = item.type;
          } else {
            // Inferir tipo baseado na descrição ou código
            const desc = (item.description || '').toLowerCase();
            const code = (item.code || '').toLowerCase();
            
            if (desc.includes('pedágio') || desc.includes('toll') || code.includes('toll')) {
              type = 'Toll';
            } else if (desc.includes('estacionamento') || desc.includes('parking') || code.includes('park')) {
              type = 'Parking';
            } else if (desc.includes('assinatura') || desc.includes('signature') || desc.includes('mensalidade')) {
              type = 'Signature';
            }
          }
          
          const current = expenseMap.get(type) || { value: 0, count: 0 };
          const itemValue = Number(item.value) || 0;
          
          expenseMap.set(type, {
            value: current.value + itemValue,
            count: current.count + 1
          });
        });
      }
      
      // Converter para array de ExpenseData com dados individuais (incluindo companyName)
      const expenseDataWithCompanies: ExpenseData[] = [];
      
      if (tollParkingResponse?.data) {
        // ✅ Aplicar o mesmo filtro para dados com companyName
        const filteredDataForCompanies = tollParkingResponse.data.filter(item => {
          const itemValue = Number(item.value) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredDataForCompanies.forEach(item => {
          // Determinar o tipo (mesmo lógica de antes)
          let type: 'Toll' | 'Parking' | 'Signature' | 'Others' = 'Others';
          
          if (item.type) {
            type = item.type;
          } else {
            const desc = (item.description || '').toLowerCase();
            const code = (item.code || '').toLowerCase();
            
            if (desc.includes('pedágio') || desc.includes('toll') || code.includes('toll')) {
              type = 'Toll';
            } else if (desc.includes('estacionamento') || desc.includes('parking') || code.includes('park')) {
              type = 'Parking';
            } else if (desc.includes('assinatura') || desc.includes('signature') || desc.includes('mensalidade')) {
              type = 'Signature';
            }
          }
          
          expenseDataWithCompanies.push({
            type,
            value: Number(item.value) || 0,
            count: 1, // Cada item conta como 1
            companyName: item.companyName || 'Empresa Não Informada'
          });
        });
      }
      
      // Para compatibilidade, manter também os dados agregados
      this.expenseData = expenseDataWithCompanies.length > 0 ? expenseDataWithCompanies : Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'Toll' | 'Parking' | 'Signature' | 'Others',
          value: data.value,
          count: data.count
        }))
        .filter(item => item.value > 0 || item.count > 0);
        

      
      // 🏢 Processar breakdown por empresa
      this.processCompanyBreakdown();
      
      // 📊 Atualizar dados dos cards
      this.updateExpenseCards();
        
    } catch (error) {
      console.error('Erro ao carregar dados de despesas:', error);
      this.expenseData = [];
      this.updateExpenseCards();
    }
  }

  // 🏢 Processar breakdown por empresa
  private processCompanyBreakdown() {
    const companyMap = new Map<string, { 
      totalValue: number; 
      totalCount: number; 
      expenses: Map<string, { value: number; count: number }> 
    }>();

    // Agrupar dados por empresa
    this.expenseData.forEach(item => {
      const companyName = item.companyName || 'Empresa Não Informada';
      
      if (!companyMap.has(companyName)) {
        companyMap.set(companyName, {
          totalValue: 0,
          totalCount: 0,
          expenses: new Map()
        });
      }
      
      const company = companyMap.get(companyName)!;
      company.totalValue += item.value;
      company.totalCount += item.count;
      
      // Agrupar por tipo dentro da empresa
      const currentExpense = company.expenses.get(item.type) || { value: 0, count: 0 };
      company.expenses.set(item.type, {
        value: currentExpense.value + item.value,
        count: currentExpense.count + item.count
      });
    });

    // Converter para array final
    this.companyBreakdown = Array.from(companyMap.entries())
      .map(([name, data]) => ({
        name,
        totalValue: data.totalValue,
        totalCount: data.totalCount,
        expenses: Array.from(data.expenses.entries())
          .map(([type, expense]) => ({
            type,
            value: expense.value,
            count: expense.count
          }))
          .sort((a, b) => b.value - a.value) // Ordenar por valor
      }))
      .sort((a, b) => b.totalValue - a.totalValue); // Ordenar empresas por valor total
  }

  // 🎨 Métodos auxiliares para o template
  formatPercentage(value: number): string {
    return `${value.toFixed(1).replace('.', ',')}%`;
  }

  getTotalValue(): number {
    return this.companyBreakdown.reduce((sum, company) => sum + company.totalValue, 0);
  }

  getTypeColor(type: string): string {
    const colors: { [key: string]: string } = {
      'Toll': '#3B82F6',
      'Parking': '#10B981', 
      'Signature': '#F59E0B',
      'Others': '#8B5CF6'
    };
    return colors[type] || '#6B7280';
  }

  getTypeLabel(type: string): string {
    const labels: { [key: string]: string } = {
      'Toll': 'Pedágios',
      'Parking': 'Estacionamentos',
      'Signature': 'Assinaturas', 
      'Others': 'Outros'
    };
    return labels[type] || type;
  }

  getTypeIcon(type: string): string {
    const icons: { [key: string]: string } = {
      'Toll': 'fas fa-road',
      'Parking': 'fas fa-parking',
      'Signature': 'fas fa-file-signature',
      'Others': 'fas fa-ellipsis-h'
    };
    return icons[type] || 'fas fa-circle';
  }

  getTypeGradient(type: string): string {
    const gradients: { [key: string]: string } = {
      'Toll': 'linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%)',
      'Parking': 'linear-gradient(135deg, #10B981 0%, #047857 100%)',
      'Signature': 'linear-gradient(135deg, #F59E0B 0%, #D97706 100%)',
      'Others': 'linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%)'
    };
    return gradients[type] || 'linear-gradient(135deg, #6B7280 0%, #4B5563 100%)';
  }

  // 📊 Carregar dados do gráfico de pagamentos e antecipações
  private async loadKPIsExpensePaymentAndAdvanceData() {
    try {
      // ✅ Usando utility para período do mês atual
      const dateFilters = DateRangeShortcuts.currentMonth();
      // Pending, Paid, Approved, ApprovedCustomer, Refused, AdvanceRequested, AdvanceApproved, AdvanceRefused
      // https://prafrota-be-bff-tenant-api.grupopra.tech/account-payable?page=1&limit=10000&status=ApprovedCustomer%2CAdvanceRequested%2CAdvanceApproved%2CAdvanceRefused%2CRequestAdvanceApproved%2CRequestAdvanceRefused

      const accountPayableResponse = await firstValueFrom(
        // this.accountPayableService.getAccountPayables(1, 10000,{date_start: dateFilters.date_start,date_end: dateFilters.date_end,status: 'ApprovedCustomer,AdvanceRequested,AdvanceApproved,AdvanceRefused,RequestAdvanceApproved,RequestAdvanceRefused'})
        this.accountPayableService.getAccountPayables(1, 10000,{date_start: dateFilters.date_start,date_end: dateFilters.date_end})        
      );

      
      // Agrupar dados por status (mapeando para os tipos desejados)
      const statusMap = new Map<string, { value: number; count: number }>();
      
      // Inicializar todos os tipos
      const paymentTypes: ('ApprovedCustomer' | 'AdvanceRequested' | 'AdvanceApproved' | 'AdvanceRefused' | 'RequestAdvanceApproved' | 'RequestAdvanceRefused')[] = 
        ['ApprovedCustomer', 'AdvanceRequested', 'AdvanceApproved', 'AdvanceRefused', 'RequestAdvanceApproved', 'RequestAdvanceRefused'];
      
      paymentTypes.forEach(type => {
        statusMap.set(type, { value: 0, count: 0 });
      });
      
      // Processar dados reais - mapeamento dos status do backend
      if (accountPayableResponse?.data) {
        accountPayableResponse.data.forEach(item => {
          // Mapear status do backend para os tipos desejados
          let mappedType: 'Pending' | 'Paid' | 'Cancelled' | 'Refused' |'Approved' |'AdvanceRequested'| 'AdvanceRefused' | 'AdvanceApproved'| 'ApprovedCustomer'| 'RequestAdvanceApproved' | 'RequestAdvanceRefused';
          
          // Mapear os status específicos que você mencionou
          const originalStatus = item.status;
          
          switch (originalStatus) {
            case 'ApprovedCustomer':
              mappedType = 'ApprovedCustomer';
              break;
            case 'AdvanceRequested':
              mappedType = 'AdvanceRequested';
              break;
            case 'AdvanceApproved':
              mappedType = 'AdvanceApproved';
              break;
            case 'AdvanceRefused':
              mappedType = 'AdvanceRefused';
              break;
            case 'RequestAdvanceApproved':
              mappedType = 'RequestAdvanceApproved';
              break;
            case 'RequestAdvanceRefused':
              mappedType = 'RequestAdvanceRefused';
              break;
            case 'Paid':
              mappedType = 'Paid';
              break;
            case 'Cancelled':
              mappedType = 'Cancelled';
              break;
            case 'Refused':
              mappedType = 'Refused';
              break;
            case 'Approved':
              mappedType = 'Approved';
              break;
            default:
              mappedType = 'Pending';
          }
          
          const current = statusMap.get(mappedType) || { value: 0, count: 0 };
          const itemValue = Number(item.total) || Number(item.amount) || 0;
          
          statusMap.set(mappedType, {
            value: current.value + itemValue,
            count: current.count + 1
          });
        });
      }
      
      // Converter para array de ExpenseData
      this.paymentAdvanceData = Array.from(statusMap.entries())
        .map(([type, data]) => ({
          type: type as 'ApprovedCustomer' | 'AdvanceRequested' | 'AdvanceApproved' | 'AdvanceRefused',
          value: data.value,
          count: data.count
        }))
        .filter(item => item.value > 0 || item.count > 0); // Mostrar apenas tipos com dados
        
      
      // 📊 Atualizar dados dos cards
      this.updateExpenseCards();
      
    } catch (error) {
      console.error('Erro ao carregar dados de pagamentos:', error);
      this.updateExpenseCards();
    }
  }

  // 📊 Atualizar dados dos cards de despesas
  private updateExpenseCards() {
    // Atualizar card de pedágio e estacionamento
    const tollCard = this.expenseCards.find(card => card.id === 'tollparking');
    if (tollCard) {
      tollCard.data = [...this.expenseData];
      tollCard.previousMonthData = [...this.previousMonthExpenseData];
      tollCard.comparison = this.calculateComparison(this.expenseData, this.previousMonthExpenseData);
    }

    // Atualizar card de pagamentos e antecipações
    const paymentsCard = this.expenseCards.find(card => card.id === 'payments');
    if (paymentsCard) {
      paymentsCard.data = [...this.paymentAdvanceData];
      paymentsCard.previousMonthData = [...this.previousMonthPaymentAdvanceData];
      paymentsCard.comparison = this.calculateComparison(this.paymentAdvanceData, this.previousMonthPaymentAdvanceData);
    }

    // Card de combustível
    const fuelCard = this.expenseCards.find(card => card.id === 'fuel');
    if (fuelCard && fuelCard.enabled) {
      fuelCard.data = [...this.fuelData];
      fuelCard.previousMonthData = [...this.previousMonthFuelData];
      fuelCard.comparison = this.calculateComparison(this.fuelData, this.previousMonthFuelData);
    }

    // Card de multas
    const finesCard = this.expenseCards.find(card => card.id === 'fines');
    if (finesCard && finesCard.enabled) {
      finesCard.data = [...this.finesData];
      finesCard.previousMonthData = [...this.previousMonthFinesData];
      finesCard.comparison = this.calculateComparison(this.finesData, this.previousMonthFinesData);
    }
  }

  // 🔄 Atualizar dados
  async refreshData() {
    try {
      await Promise.all([
        // Dados de rotas
        this.loadRoutes(),
        this.loadFleetTypes(),
        // Dados dos KPIs
        this.loadKPIs(),
        // Dados do mês atual
        this.loadKPIsExpenseTollParkingData(),
        this.loadKPIsExpensePaymentAndAdvanceData(),
        this.loadKPIsExpenseFuelData(),
        this.loadKPIsExpenseFinesData(),
        // ✨ Dados do mês anterior
        this.loadPreviousMonthTollParkingData(),
        this.loadPreviousMonthPaymentAndAdvanceData(),
        this.loadPreviousMonthFuelData(),
        this.loadPreviousMonthFinesData()
      ]);
      this.lastUpdate = new Date().toLocaleTimeString('pt-BR');
    } catch (error) {
      console.error('Erro ao atualizar dados:', error);
    }
  }

  // 🎯 Métodos para interação
  onVehicleAction(event: { action: string; data: any }) {
    console.log('Ação do veículo:', event);
    // Implementar navegação ou ações específicas
  }

  // 📊 Obter classe CSS para trend
  getTrendClass(trend: string): string {
    switch (trend) {
      case 'up': return 'trend-up';
      case 'down': return 'trend-down';
      default: return 'trend-stable';
    }
  }

  // 🎨 Obter classe CSS para cor do KPI
  getKpiColorClass(color: string): string {
    return `kpi-${color}`;
  }

  // ⏰ Obter próximo horário de sincronização
  getNextSyncTime(): string {
    const now = new Date();
    const nextSync = new Date(now.getTime() + 30 * 60 * 1000); // 30 minutos
    return nextSync.toLocaleTimeString('pt-BR', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }

  // 💰 Formatação inteligente de valores monetários
  formatCurrency(value: number): string {
    if (!value || value === 0) return 'R$ 0,00';
    
    const absValue = Math.abs(value);
    
    if (absValue >= 1000000000) {
      // Bilhões
      return `R$ ${(value / 1000000000).toFixed(1).replace('.', ',')}B`;
    } else if (absValue >= 1000000) {
      // Milhões
      return `R$ ${(value / 1000000).toFixed(1).replace('.', ',')}M`;
    } else if (absValue >= 1000) {
      // Milhares
      return `R$ ${(value / 1000).toFixed(1).replace('.', ',')}K`;
    } else {
      // Valores normais
      return value.toLocaleString('pt-BR', { 
        style: 'currency', 
        currency: 'BRL',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    }
  }

  // ✨ NOVOS MÉTODOS: Buscar dados do mês anterior

  /**
   * 📊 Carregar dados de pedágio e estacionamento do mês anterior
   */
  private async loadPreviousMonthTollParkingData() {
    try {
      const dateFilters = DateRangeShortcuts.previousMonth();
      
      const tollParkingResponse = await firstValueFrom(
        this.tollParkingService.getTollparkingsDashboardList(1, 10000, dateFilters)        
      );
      
      // Processar dados (mesma lógica do mês atual)
      const expenseMap = new Map<string, { value: number; count: number }>();
      const types: ('Toll' | 'Parking' | 'Signature' | 'Others')[] = ['Toll', 'Parking', 'Signature', 'Others'];
      
      types.forEach(type => {
        expenseMap.set(type, { value: 0, count: 0 });
      });
      
      if (tollParkingResponse?.data) {
        const filteredData = tollParkingResponse.data.filter(item => {
          const itemValue = Number(item.value) || 0;
          return itemValue >= 0;
        });
        
        filteredData.forEach(item => {
          let type: 'Toll' | 'Parking' | 'Signature' | 'Others' = 'Others';
          
          if (item.type) {
            type = item.type;
          } else {
            const desc = (item.description || '').toLowerCase();
            const code = (item.code || '').toLowerCase();
            
            if (desc.includes('pedágio') || desc.includes('toll') || code.includes('toll')) {
              type = 'Toll';
            } else if (desc.includes('estacionamento') || desc.includes('parking') || code.includes('park')) {
              type = 'Parking';
            } else if (desc.includes('assinatura') || desc.includes('signature') || desc.includes('mensalidade')) {
              type = 'Signature';
            }
          }
          
          const current = expenseMap.get(type) || { value: 0, count: 0 };
          const itemValue = Number(item.value) || 0;
          
          expenseMap.set(type, {
            value: current.value + itemValue,
            count: current.count + 1
          });
        });
      }
      
      this.previousMonthExpenseData = Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'Toll' | 'Parking' | 'Signature' | 'Others',
          value: data.value,
          count: data.count
        }))
        .filter(item => item.value > 0 || item.count > 0);
        
    } catch (error) {
      console.error('Erro ao carregar dados de pedágio do mês anterior:', error);
      this.previousMonthExpenseData = [];
    }
  }

  /**
   * 📊 Carregar dados de combustível do mês anterior
   */
  private async loadPreviousMonthFuelData() {
    try {
      const dateFilters = DateRangeShortcuts.previousMonth();
      
      const fuelResponse = await firstValueFrom(
        this.fuelService.getFuelcontrollsDashboardList(1, 100000, {start_date: dateFilters.date_start, end_date: dateFilters.date_end})        
      );

        // Agrupar dados por tipo
      const expenseMap = new Map<string, { totalValue: number; totalSupplies: number }>();
      
      // Inicializar todos os tipos
      const types: ('Fuel' | 'Others')[] = ['Fuel', 'Others'];
      types.forEach(type => {
        expenseMap.set(type, { totalValue: 0, totalSupplies: 0 });
      });
      
      // Processar dados reais
      if (fuelResponse?.data) {
        // ✅ Filtrar registros com valor negativo
        const filteredData = fuelResponse.data.filter(item => {
          const itemValue = Number(item.totalValue) || 0;
          return itemValue >= 0; // Manter apenas valores positivos ou zero
        });
        
        filteredData.forEach(item => {
          // Determinar o tipo baseado no campo type ou inferir de outros campos
          let type: 'Fuel' | 'Others' = 'Others';
          
          if (item.type && (item.type === 'Fuel' || item.type === 'Others')) {
            type = item.type;
          }
          
          const current = expenseMap.get(type) || { totalValue: 0, totalSupplies: 0 };
          const itemValue = Number(item.totalValue) || 0;
              
          expenseMap.set(type, {
            totalValue: current.totalValue + itemValue,
            totalSupplies: current.totalSupplies + 1
          });
        });
      }
      
      this.previousMonthFuelData = Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'Fuel' | 'Others',
          value: data.totalValue,
          count: data.totalSupplies
        }))
        .filter(item => item.value > 0 || item.count > 0);
        
    } catch (error) {
      console.error('Erro ao carregar dados de combustível do mês anterior:', error);
      this.previousMonthFuelData = [];
    }
  }

  /**
   * 📊 Carregar dados de multas do mês anterior
   */
  private async loadPreviousMonthFinesData() {
    try {
      const dateFilters = DateRangeShortcuts.previousMonth();
      
      const finesResponse = await firstValueFrom(
        this.finesService.getVehicleFinesDashboardList(1, 100000, {start_due_date: dateFilters.date_start, end_due_date: dateFilters.date_end})        
      );
      
      const expenseMap = new Map<string, { fineValue: number; totalFine: number }>();
      const types: ('GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE')[] = ['GRAVISSIMA', 'GRAVE', 'MÉDIA', 'LEVE'];
      
      types.forEach(type => {
        expenseMap.set(type, { fineValue: 0, totalFine: 0 });
      });

      if (finesResponse?.data) {
        const filteredData = finesResponse.data.filter(item => {
          const itemValue = Number(item.fine_value) || 0;
          return itemValue >= 0;
        });
        
        filteredData.forEach(item => {
          let type: 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE' = 'LEVE';
          
          if (item.severity) {
            type = this.mapSeverityToType(item.severity) as 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE';
          }
          
          const current = expenseMap.get(type) || { fineValue: 0, totalFine: 0 };
          const itemValue = Number(item.fine_value) || 0;
          
          expenseMap.set(type, {
            fineValue: current.fineValue + itemValue,
            totalFine: current.totalFine + 1
          });
        });
      }
      
      this.previousMonthFinesData = Array.from(expenseMap.entries())
        .map(([type, data]) => ({
          type: type as 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE',
          value: data.fineValue,
          count: data.totalFine
        }))
        .filter(item => item.value > 0 || item.count > 0);
        
    } catch (error) {
      console.error('Erro ao carregar dados de multas do mês anterior:', error);
      this.previousMonthFinesData = [];
    }
  }

  /**
   * 📊 Carregar dados de pagamentos do mês anterior
   */
  private async loadPreviousMonthPaymentAndAdvanceData() {
    try {
      const dateFilters = DateRangeShortcuts.previousMonth();
      
      const accountPayableResponse = await firstValueFrom(
        this.accountPayableService.getAccountPayables(1, 10000, {date_start: dateFilters.date_start, date_end: dateFilters.date_end})        
      );

      const statusMap = new Map<string, { value: number; count: number }>();
      const paymentTypes: ('ApprovedCustomer' | 'AdvanceRequested' | 'AdvanceApproved' | 'AdvanceRefused' | 'RequestAdvanceApproved' | 'RequestAdvanceRefused')[] = 
        ['ApprovedCustomer', 'AdvanceRequested', 'AdvanceApproved', 'AdvanceRefused', 'RequestAdvanceApproved', 'RequestAdvanceRefused'];
      
      paymentTypes.forEach(type => {
        statusMap.set(type, { value: 0, count: 0 });
      });
      
      if (accountPayableResponse?.data) {
        accountPayableResponse.data.forEach(item => {
          let mappedType: 'Pending' | 'Paid' | 'Cancelled' | 'Refused' |'Approved' |'AdvanceRequested'| 'AdvanceRefused' | 'AdvanceApproved'| 'ApprovedCustomer'| 'RequestAdvanceApproved' | 'RequestAdvanceRefused';
          
          const originalStatus = item.status;
          
          switch (originalStatus) {
            case 'ApprovedCustomer': mappedType = 'ApprovedCustomer'; break;
            case 'AdvanceRequested': mappedType = 'AdvanceRequested'; break;
            case 'AdvanceApproved': mappedType = 'AdvanceApproved'; break;
            case 'AdvanceRefused': mappedType = 'AdvanceRefused'; break;
            case 'RequestAdvanceApproved': mappedType = 'RequestAdvanceApproved'; break;
            case 'RequestAdvanceRefused': mappedType = 'RequestAdvanceRefused'; break;
            case 'Paid': mappedType = 'Paid'; break;
            case 'Cancelled': mappedType = 'Cancelled'; break;
            case 'Refused': mappedType = 'Refused'; break;
            case 'Approved': mappedType = 'Approved'; break;
            default: mappedType = 'Pending';
          }
          
          const current = statusMap.get(mappedType) || { value: 0, count: 0 };
          const itemValue = Number(item.total) || Number(item.amount) || 0;
          
          statusMap.set(mappedType, {
            value: current.value + itemValue,
            count: current.count + 1
          });
        });
      }
      
      this.previousMonthPaymentAdvanceData = Array.from(statusMap.entries())
        .map(([type, data]) => ({
          type: type as 'ApprovedCustomer' | 'AdvanceRequested' | 'AdvanceApproved' | 'AdvanceRefused',
          value: data.value,
          count: data.count
        }))
        .filter(item => item.value > 0 || item.count > 0);
        
    } catch (error) {
      console.error('Erro ao carregar dados de pagamentos do mês anterior:', error);
      this.previousMonthPaymentAdvanceData = [];
    }
  }

  /**
   * ✨ Calcular comparação entre mês atual e anterior
   */
  private calculateComparison(currentData: ExpenseData[], previousData: ExpenseData[]): MonthlyComparison {
    const currentTotal = currentData.reduce((sum, item) => sum + item.value, 0);
    const previousTotal = previousData.reduce((sum, item) => sum + item.value, 0);
    const currentCount = currentData.reduce((sum, item) => sum + item.count, 0);
    const previousCount = previousData.reduce((sum, item) => sum + item.count, 0);
    
    let percentageChange = 0;
    if (previousTotal > 0) {
      percentageChange = Math.abs(((currentTotal - previousTotal) / previousTotal) * 100);
    }
    
    let trend: 'up' | 'down' | 'stable' = 'stable';
    if (previousTotal > 0) {
      const changeRatio = (currentTotal - previousTotal) / previousTotal;
      if (changeRatio > 0.05) { // Mais de 5% de aumento
        trend = 'up';
      } else if (changeRatio < -0.05) { // Mais de 5% de redução
        trend = 'down';
      }
    }
    
    return {
      currentTotal,
      previousTotal,
      percentageChange,
      trend,
      currentCount,
      previousCount
    };
  }

  /**
   * 🎯 Mapeia todos os tipos de severity para categorias principais
   */
  private mapSeverityToType(severity: string): 'GRAVISSIMA' | 'GRAVE' | 'MÉDIA' | 'LEVE' {
    if (!severity) return 'LEVE';
    
    const severityUpper = severity.toUpperCase();
    
    // 🎯 PRIORIDADE: Mapeamento completo de GRAVISSIMA e suas variações
    if (severityUpper.includes('GRAVISSIMA') || severityUpper.includes('GRAVÍSSIMA')) {
      return 'GRAVISSIMA';
    }
    
    // Mapeamento específico para todos os casos de GRAVISSIMA
    if (severityUpper === 'GRAVISSIMA' ||
        severityUpper === 'GRAVISSIMA_1X' ||
        severityUpper === 'GRAVISSIMA_2X' ||
        severityUpper === 'GRAVISSIMA_3X' ||
        severityUpper === 'GRAVISSIMA_4X' ||
        severityUpper === 'GRAVISSIMA_5X' ||
        severityUpper === 'GRAVISSIMA_6X' ||
        severityUpper === 'GRAVISSIMA_7X' ||
        severityUpper === 'GRAVISSIMA_8X' ||
        severityUpper === 'GRAVISSIMA_9X' ||
        severityUpper === 'GRAVISSIMA_10X') {
      return 'GRAVISSIMA';
    }
    
    // Outros tipos
    if (severityUpper.includes('GRAVE')) {
      return 'GRAVE';
    }
    
    if (severityUpper.includes('MEDIA') || severityUpper.includes('MÉDIA')) {
      return 'MÉDIA';
    }
    
    if (severityUpper.includes('LEVE')) {
      return 'LEVE';
    }
    
    // Mapeamento específico para casos especiais
    switch (severityUpper) {
      case 'GRAVE':
        return 'GRAVE';
      
      case 'MEDIA':
      case 'MÉDIA':
        return 'MÉDIA';
      
      case 'LEVE':
        return 'LEVE';
      
      default:
        // Para valores não reconhecidos, tentar inferir pela primeira palavra
        if (severityUpper.startsWith('GRAV')) {
          return 'GRAVISSIMA';
        } else if (severityUpper.startsWith('GRAVE')) {
          return 'GRAVE';
        } else if (severityUpper.startsWith('MED')) {
          return 'MÉDIA';
        } else {
          return 'LEVE';
        }
    }
  }
}