import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Tollparking } from '../tollparking.interface';

/**
 * 🎯 TollparkingDashboardComponent - Dashboard Personalizado para Pedágio & Estacionamento
 * 
 * ✨ Funcionalidades:
 * - Top 10 veículos por valor totalizado
 * - Evolução dos últimos 3 meses
 * - Quantidade de veículos únicos
 * - Distribuição por tipo (Pedágio, Estacionamento, etc)
 * - Gráficos e KPIs personalizados
 */
@Component({
  selector: 'app-tollparking-dashboard',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './tollparking-dashboard.component.html',
  styleUrl: './tollparking-dashboard.component.scss'
})
export class TollparkingDashboardComponent implements OnInit, OnChanges {
  @Input() entities: Tollparking[] = [];
  @Input() totalItems: number = 0;
  @Input() isLoading: boolean = false;

  // Dados processados para o dashboard
  topVehicles: VehicleStats[] = [];
  monthlyEvolution: MonthlyData[] = [];
  typeDistribution: TypeStats[] = [];
  kpis: DashboardKPI[] = [];

  ngOnInit() {
    this.processData();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['entities'] && this.entities.length > 0) {
      this.processData();
    }
  }

  /**
   * 📊 Processar dados para o dashboard
   */
  private processData(): void {
    if (!this.entities || this.entities.length === 0) {
      this.resetData();
      return;
    }

    console.log('🔄 Processando dados do dashboard...', this.entities.length, 'registros');

    this.topVehicles = this.calculateTopVehicles();
    this.monthlyEvolution = this.calculateMonthlyEvolution();
    this.typeDistribution = this.calculateTypeDistribution();
    this.kpis = this.calculateKPIs();

    console.log('✅ Dados processados:', {
      topVehicles: this.topVehicles.length,
      monthlyEvolution: this.monthlyEvolution.length,
      typeDistribution: this.typeDistribution.length,
      kpis: this.kpis.length
    });
  }

  /**
   * 🔄 Resetar dados quando não há entidades
   */
  private resetData(): void {
    this.topVehicles = [];
    this.monthlyEvolution = [];
    this.typeDistribution = [];
    this.kpis = [];
  }

  /**
   * 🏆 Calcular top 10 veículos por valor total
   */
  private calculateTopVehicles(): VehicleStats[] {
    const vehicleMap = new Map<string, VehicleStats>();

    this.entities.forEach(item => {
      const plate = item.license_plate;
      const value = Number(item.value) || 0;

      if (!vehicleMap.has(plate)) {
        vehicleMap.set(plate, {
          license_plate: plate,
          totalValue: 0,
          count: 0,
          avgValue: 0,
          lastDate: item.date || item.created_at || new Date().toISOString()
        });
      }

      const stats = vehicleMap.get(plate)!;
      stats.totalValue += value;
      stats.count += 1;
      stats.avgValue = stats.totalValue / stats.count;
      
      // Manter a data mais recente
      if (item.date && item.created_at) {
        const itemDate = new Date(item.date);
        const currentLastDate = new Date(stats.lastDate);
        if (itemDate > currentLastDate) {
          stats.lastDate = item.date;
        }
      }
    });

    return Array.from(vehicleMap.values())
      .sort((a, b) => b.totalValue - a.totalValue)
      .slice(0, 10);
  }

  /**
   * 📈 Calcular evolução dos últimos 3 meses
   */
  private calculateMonthlyEvolution(): MonthlyData[] {
    const now = new Date();
    const monthlyData: MonthlyData[] = [];

    for (let i = 2; i >= 0; i--) {
      const monthDate = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const nextMonthDate = new Date(now.getFullYear(), now.getMonth() - i + 1, 1);
      
      const monthItems = this.entities.filter(item => {
        const dateStr = item.date || item.created_at;
        if (!dateStr) return false;
        const itemDate = new Date(dateStr);
        return itemDate >= monthDate && itemDate < nextMonthDate;
      });

      const totalValue = monthItems.reduce((sum, item) => sum + (Number(item.value) || 0), 0);
      const uniqueVehicles = new Set(monthItems.map(item => item.license_plate)).size;

      monthlyData.push({
        month: monthDate.toLocaleDateString('pt-BR', { month: 'short', year: 'numeric' }),
        totalValue,
        count: monthItems.length,
        uniqueVehicles,
        avgValue: monthItems.length > 0 ? totalValue / monthItems.length : 0
      });
    }

    return monthlyData;
  }

  /**
   * 🥧 Calcular distribuição por tipo
   */
  private calculateTypeDistribution(): TypeStats[] {
    const typeMap = new Map<string, TypeStats>();

    this.entities.forEach(item => {
      const type = item.type || 'Others';
      
      if (!typeMap.has(type)) {
        typeMap.set(type, {
          type,
          label: this.getTypeLabel(type),
          count: 0,
          totalValue: 0,
          percentage: 0
        });
      }

      const stats = typeMap.get(type)!;
      stats.count += 1;
      stats.totalValue += Number(item.value) || 0;
    });

    // Calcular percentuais
    const total = this.entities.length;
    const result = Array.from(typeMap.values());
    result.forEach(stat => {
      stat.percentage = total > 0 ? (stat.count / total) * 100 : 0;
    });

    return result.sort((a, b) => b.totalValue - a.totalValue);
  }

  /**
   * 📊 Calcular KPIs principais
   */
  private calculateKPIs(): DashboardKPI[] {
    const totalValue = this.entities.reduce((sum, item) => sum + (Number(item.value) || 0), 0);
    const uniqueVehicles = new Set(this.entities.map(item => item.license_plate)).size;
    const avgValue = this.entities.length > 0 ? totalValue / this.entities.length : 0;

    // Dados dos últimos 30 dias para comparação
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    
    const recentItems = this.entities.filter(item => {
      const dateStr = item.date || item.created_at;
      if (!dateStr) return false;
      const itemDate = new Date(dateStr);
      return itemDate >= thirtyDaysAgo;
    });

    const recentValue = recentItems.reduce((sum, item) => sum + (Number(item.value) || 0), 0);
    const recentVehicles = new Set(recentItems.map(item => item.license_plate)).size;

    return [
      {
        id: 'total-value',
        label: 'Valor Total',
        value: `R$ ${totalValue.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`,
        icon: 'fas fa-dollar-sign',
        color: 'primary',
        description: 'Valor total acumulado'
      },
      {
        id: 'unique-vehicles',
        label: 'Veículos Únicos',
        value: uniqueVehicles.toString(),
        icon: 'fas fa-car',
        color: 'info',
        description: 'Quantidade de veículos diferentes'
      },
      {
        id: 'avg-value',
        label: 'Valor Médio',
        value: `R$ ${avgValue.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`,
        icon: 'fas fa-calculator',
        color: 'success',
        description: 'Valor médio por registro'
      },
      {
        id: 'recent-activity',
        label: 'Atividade Recente',
        value: recentItems.length.toString(),
        icon: 'fas fa-clock',
        color: 'warning',
        description: 'Registros dos últimos 30 dias'
      }
    ];
  }

  /**
   * 🏷️ Obter label traduzido do tipo
   */
  private getTypeLabel(type: string): string {
    const typeLabels: { [key: string]: string } = {
      'Toll': 'Pedágio',
      'Parking': 'Estacionamento', 
      'Signature': 'Assinatura',
      'Others': 'Outros'
    };
    return typeLabels[type] || type;
  }

  /**
   * 🎨 Obter cor para o tipo
   */
  getTypeColor(type: string): string {
    const typeColors: { [key: string]: string } = {
      'Toll': '#FF6B6B',      // Vermelho
      'Parking': '#4ECDC4',   // Verde água
      'Signature': '#45B7D1', // Azul
      'Others': '#96CEB4'     // Verde claro
    };
    return typeColors[type] || '#95A5A6';
  }

  /**
   * 📊 Obter largura da barra para gráfico
   */
  getBarWidth(value: number, maxValue: number): number {
    return maxValue > 0 ? (value / maxValue) * 100 : 0;
  }

  /**
   * 💰 Formatar valor monetário
   */
  formatCurrency(value: number): string {
    return `R$ ${value.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;
  }

  /**
   * 🔢 Formatar percentual
   */
  formatPercentage(value: number): string {
    return `${value.toFixed(1)}%`;
  }
}

// ========================================
// 🎯 INTERFACES
// ========================================

interface VehicleStats {
  license_plate: string;
  totalValue: number;
  count: number;
  avgValue: number;
  lastDate: string;
}

interface MonthlyData {
  month: string;
  totalValue: number;
  count: number;
  uniqueVehicles: number;
  avgValue: number;
}

interface TypeStats {
  type: string;
  label: string;
  count: number;
  totalValue: number;
  percentage: number;
}

interface DashboardKPI {
  id: string;
  label: string;
  value: string;
  icon: string;
  color: string;
  description: string;
}
