import { Component, OnInit, OnDestroy, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';

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

/**
 * 🎯 RoutesPerformanceDashboardComponent
 * 
 * Dashboard futurista para monitoramento de performance de rotas
 * Visual estilo ficção científica com efeitos neon e glassmorphism
 */
@Component({
  selector: 'app-routes-performance-dashboard',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './routes-performance-dashboard.component.html',
  styleUrl: './routes-performance-dashboard.component.scss'
})
export class RoutesPerformanceDashboardComponent implements OnInit, OnDestroy {
  
  @Input() compactMode: boolean = false;
  @Input() showFilters: boolean = true;
  @Input() autoRefresh: boolean = true;
  @Input() refreshInterval: number = 30000; // 30 segundos

  // ========================================
  // 📊 DADOS DO DASHBOARD
  // ========================================
  dashboardData: RoutesPerformanceDashboard | null = null;
  isLoading: boolean = true;
  error: string | null = null;

  // Métricas individuais para facilitar o template
  routeStatus: RouteStatusMetrics | null = null;
  vehicleMetrics: VehicleMetrics | null = null;
  driverMetrics: DriverMetrics | null = null;
  transportModal: TransportModalMetrics | null = null;
  operationalMetrics: OperationalMetrics | null = null;
  volumeMetrics: VolumeMetrics | null = null;

  // ========================================
  // 🔧 CONFIGURAÇÕES E FILTROS
  // ========================================
  currentFilters: DashboardFilters | null = null;
  timePeriods: TimePeriod[] = [];
  selectedPeriod: TimePeriod | null = null;

  // ========================================
  // 🎨 ESTADO VISUAL
  // ========================================
  animationsEnabled: boolean = true;
  lastUpdated: Date | null = null;
  refreshTimer: any;

  private subscriptions = new Subscription();

  constructor(
    private routesPerformanceService: RoutesPerformanceService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.initializeDashboard();
    this.setupAutoRefresh();
  }

  ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  }

  // ========================================
  // 🚀 INICIALIZAÇÃO
  // ========================================

  private initializeDashboard(): void {
    this.loadTimePeriods();
    this.subscribeToData();
    this.subscribeToFilters();
    this.loadDashboardData();
  }

  private loadTimePeriods(): void {
    const periodsSubscription = this.routesPerformanceService.getTimePeriods().subscribe({
      next: (periods) => {
        this.timePeriods = periods;
        this.selectedPeriod = periods.find(p => p.active) || periods[0];
        this.cdr.markForCheck();
      },
      error: (error) => {
        console.error('Erro ao carregar períodos:', error);
      }
    });

    this.subscriptions.add(periodsSubscription);
  }

  private subscribeToData(): void {
    const dataSubscription = this.routesPerformanceService.dashboardData$.subscribe({
      next: (data) => {
        if (data) {
          this.dashboardData = data;
          this.extractMetrics(data);
          this.lastUpdated = data.lastUpdated;
          this.isLoading = false;
          this.error = null;
          this.cdr.markForCheck();
        }
      },
      error: (error) => {
        this.error = 'Erro ao carregar dados do dashboard';
        this.isLoading = false;
        console.error('Erro no dashboard:', error);
        this.cdr.markForCheck();
      }
    });

    this.subscriptions.add(dataSubscription);
  }

  private subscribeToFilters(): void {
    const filtersSubscription = this.routesPerformanceService.filters$.subscribe({
      next: (filters) => {
        this.currentFilters = filters;
        this.cdr.markForCheck();
      }
    });

    this.subscriptions.add(filtersSubscription);
  }

  private extractMetrics(data: RoutesPerformanceDashboard): void {
    this.routeStatus = data.routeStatus;
    this.vehicleMetrics = data.vehicleMetrics;
    this.driverMetrics = data.driverMetrics;
    this.transportModal = data.transportModal;
    this.operationalMetrics = data.operationalMetrics;
    this.volumeMetrics = data.volumeMetrics;
  }

  // ========================================
  // 📊 CARREGAMENTO DE DADOS
  // ========================================

  private loadDashboardData(): void {
    this.isLoading = true;
    this.error = null;

    const loadSubscription = this.routesPerformanceService.getDashboardData(this.currentFilters || undefined).subscribe({
      next: (data) => {
        // Dados são atualizados via subscription do dashboardData$
      },
      error: (error) => {
        this.error = 'Erro ao carregar dados';
        this.isLoading = false;
        console.error('Erro ao carregar dashboard:', error);
        this.cdr.markForCheck();
      }
    });

    this.subscriptions.add(loadSubscription);
  }

  // ========================================
  // 🔄 AUTO REFRESH
  // ========================================

  private setupAutoRefresh(): void {
    if (this.autoRefresh && this.refreshInterval > 0) {
      this.refreshTimer = setInterval(() => {
        this.refreshData();
      }, this.refreshInterval);
    }
  }

  public refreshData(): void {
    this.loadDashboardData();
  }

  // ========================================
  // 🎛️ CONTROLES DE FILTRO
  // ========================================

  onPeriodChange(period: TimePeriod): void {
    this.selectedPeriod = period;
    
    // Calcular datas baseado no tipo de período
    const { startDate, endDate } = this.calculateDateRange(period.id);
    
    this.routesPerformanceService.updateFilters({
      dateRange: {
        start: startDate,
        end: endDate
      }
    });
  }

  /**
   * Calcula o range de datas baseado no período selecionado
   */
  private calculateDateRange(periodId: string): { startDate: Date; endDate: Date } {
    const now = new Date();
    let startDate: Date;
    let endDate: Date = new Date(now);

    switch (periodId) {
      case 'today':
        // Hoje: do início do dia até agora
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
        endDate = new Date(now);
        break;

      case 'current-month':
        // Mês atual: do primeiro dia do mês até agora
        startDate = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
        endDate = new Date(now);
        break;

      case 'current-year':
        // Ano atual: do primeiro dia do ano até agora
        startDate = new Date(now.getFullYear(), 0, 1, 0, 0, 0);
        endDate = new Date(now);
        break;

      case '7d':
        // Últimos 7 dias
        startDate = new Date(Date.now() - (7 * 24 * 60 * 60 * 1000));
        break;

      case '30d':
        // Últimos 30 dias
        startDate = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000));
        break;

      case '90d':
        // Últimos 90 dias
        startDate = new Date(Date.now() - (90 * 24 * 60 * 60 * 1000));
        break;

      case '1y':
        // Último ano
        startDate = new Date(Date.now() - (365 * 24 * 60 * 60 * 1000));
        break;

      default:
        // Fallback para últimos 30 dias
        startDate = new Date(Date.now() - (30 * 24 * 60 * 60 * 1000));
    }

    return { startDate, endDate };
  }

  // ========================================
  // 🎨 MÉTODOS UTILITÁRIOS PARA TEMPLATE
  // ========================================

  formatNumber(value: number, type: 'currency' | 'percentage' | 'decimal' = 'decimal'): string {
    return this.routesPerformanceService.formatNumber(value, type);
  }

  getTrendColor(trend: 'up' | 'down' | 'stable'): string {
    return this.routesPerformanceService.getTrendColor(trend);
  }

  getTrendIcon(trend: 'up' | 'down' | 'stable'): string {
    return this.routesPerformanceService.getTrendIcon(trend);
  }

  getRelativeTime(date: Date): string {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    
    if (diffMinutes < 1) return 'agora mesmo';
    if (diffMinutes < 60) return `${diffMinutes}min atrás`;
    
    const diffHours = Math.floor(diffMinutes / 60);
    if (diffHours < 24) return `${diffHours}h atrás`;
    
    const diffDays = Math.floor(diffHours / 24);
    return `${diffDays}d atrás`;
  }

  // ========================================
  // 🎯 GETTERS PARA TEMPLATE
  // ========================================

  get hasData(): boolean {
    return this.dashboardData !== null && !this.isLoading;
  }

  get showLoadingState(): boolean {
    return this.isLoading && this.dashboardData === null;
  }

  get showErrorState(): boolean {
    return this.error !== null && !this.isLoading;
  }

  get totalRoutes(): number {
    return this.routeStatus?.total || 0;
  }

  get totalVehicles(): number {
    return this.vehicleMetrics?.totalVehicles || 0;
  }

  get totalDrivers(): number {
    return this.driverMetrics?.totalDrivers || 0;
  }

  get totalCost(): number {
    return this.operationalMetrics?.totalCost || 0;
  }

  get totalVolumes(): number {
    return this.volumeMetrics?.totalVolumes || 0;
  }

  // ========================================
  // 🎨 ANIMAÇÕES E EFEITOS
  // ========================================

  onCardHover(event: MouseEvent, cardType: string): void {
    if (!this.animationsEnabled) return;
    
    const card = event.currentTarget as HTMLElement;
    card.style.transform = 'translateY(-4px) scale(1.02)';
    card.style.boxShadow = '0 20px 40px rgba(0, 212, 255, 0.3)';
  }

  onCardLeave(event: MouseEvent, cardType: string): void {
    if (!this.animationsEnabled) return;
    
    const card = event.currentTarget as HTMLElement;
    card.style.transform = 'translateY(0) scale(1)';
    card.style.boxShadow = '0 8px 32px rgba(0, 0, 0, 0.3)';
  }

  toggleAnimations(): void {
    this.animationsEnabled = !this.animationsEnabled;
  }
}
