import { ChangeDetectorRef, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouteMapComponent, MapStats } from '../route-stops/components/route-map/route-map.component';
import { RouteStepsService } from './route-steps.service';
import { RouteStep } from './route-steps.interface';
import { RoutesService } from '../routes.service';
import { Route } from '../route.interface';

@Component({
  selector: 'app-route-steps',
  standalone: true,
  imports: [CommonModule, RouteMapComponent],
  templateUrl: './route-steps.component.html',
  styleUrl: './route-steps.component.scss'
})
export class RouteStepsComponent implements OnInit, OnDestroy {
  @Input() routeData?: any;
  
  // 🎯 PROPRIEDADES DO COMPONENTE
  routeSteps: RouteStep[] = [];
  routeInfo: Route | null = null;
  mapStats: MapStats = {
    totalStops: 0,
    intermediateStops: 0,
    totalDistance: '0 km',
    estimatedTime: '0 min'
  };
  isLoading = true;
  hasError = false;
  errorMessage = '';
  
  constructor(
    private routeStepsService: RouteStepsService,
    private routesService: RoutesService,
    private cdr: ChangeDetectorRef
    ) {
    
    console.log('🚀 [RouteStepsComponent] Componente inicializado!');
    console.log('🔍 [RouteStepsComponent] routeData:', this.routeData);
  }

  ngOnInit(): void {
    console.log('🚀 [RouteStepsComponent] ngOnInit');
    console.log('🔍 [RouteStepsComponent] routeData:', this.routeData);
    
    // 🎯 DETERMINA O ROUTE ID
    const routeId = this.routeData?.routeId || this.routeData?.id || 'route_1';
    console.log('🎯 [RouteStepsComponent] Usando routeId:', routeId);
    
    // 🎯 CARREGA DADOS DA ROTA E STEPS
    this.loadRouteData(routeId);
    this.loadRouteSteps(routeId);
  }

  ngOnDestroy(): void {
    console.log('🔥 [RouteStepsComponent] ngOnDestroy');
  }

  // ========================================
  // 🎯 MÉTODOS DE CARREGAMENTO DE DADOS
  // ========================================

  private loadRouteData(routeId: string): void {
    console.log('📁 [RouteStepsComponent] Carregando dados da rota:', routeId);
    
    this.routesService.getById(routeId).subscribe({
      next: (route: Route) => {
        console.log('✅ [RouteStepsComponent] Dados da rota carregados:', route);
        this.routeInfo = route;
        this.cdr.detectChanges();
      },
      error: (error) => {
        console.error('❌ [RouteStepsComponent] Erro ao carregar dados da rota:', error);
        // Se não conseguir carregar da API, criar dados mock para fallback
        this.routeInfo = this.createMockRouteInfo(routeId);
        this.cdr.detectChanges();
      }
    });
  }

  private loadRouteSteps(routeId: string): void {
    console.log('📁 [RouteStepsComponent] Carregando steps da rota:', routeId);
    this.isLoading = true;
    this.hasError = false;

    this.routeStepsService.getRouteSteps(routeId).subscribe({
      next: (steps: RouteStep[]) => {
        console.log('✅ [RouteStepsComponent] Steps carregados com sucesso:', steps.length);
        console.log('🔍 [RouteStepsComponent] Dados dos steps:', steps);
        
        this.routeSteps = steps;
        this.isLoading = false;
        this.cdr.detectChanges();
        
        console.log('🎯 [RouteStepsComponent] routeSteps atualizado para o mapa:', this.routeSteps.length);
      },
      error: (error) => {
        console.error('❌ [RouteStepsComponent] Erro ao carregar steps:', error);
        this.hasError = true;
        this.errorMessage = 'Erro ao carregar etapas da rota';
        this.isLoading = false;
        this.cdr.detectChanges();
      }
    });
  }

  private createMockRouteInfo(Id: string): Route {
    return {
      Id: Id,
      routeNumber: 'RT-2024-001',
      companyId: 'company_1',
      type: 'lastMile',
      status: 'inProgress',
      priority: 'normal',
      description: 'Teste de Rendering',
      
      // 🚛 DADOS DO VEÍCULO E MOTORISTA
      driverId: 'driver_1',
      driverName: 'João Silva',
      driverRating: 4.8,
      vehicleId: 'vehicle_1',
      vehiclePlate: 'ABC-1234',
      vehicleType: 'Mercedes Sprinter',
      
      // 📍 LOCALIZAÇÕES
      origin: {
        address: 'Centro de Distribuição - São Paulo',
        city: 'São Paulo',
        state: 'SP',
        zipCode: '01310-100'
      },
      destination: {
        address: 'Região Metropolitana - São Paulo',
        city: 'São Paulo',
        state: 'SP',
        zipCode: '04567-890'
      },
      
      // ⏰ CRONOGRAMA
      scheduledDeparture: new Date('2024-01-15T08:00:00'),
      scheduledArrival: new Date('2024-01-15T16:00:00'),
      actualDeparture: new Date('2024-01-15T08:15:00'),
      
      // 📊 MÉTRICAS
      totalDistance: 45,
      estimatedDuration: 480, // 8 horas
      actualDuration: 180, // 3 horas parcial
      totalValue: 850.00,
      
      // 🗃️ METADADOS
      createdAt: new Date(),
      updatedAt: new Date()
    } as Route;
  }

  // ========================================
  // 🎯 EVENTOS DO MAPA
  // ========================================

  onStepSelected(step: RouteStep): void {
    console.log('📍 [RouteStepsComponent] Step selecionado no mapa:', step);
  }

  onMapReady(ready: boolean): void {
    console.log('🗺️ [RouteStepsComponent] Mapa pronto:', ready);
  }

  onMapStatsUpdated(stats: MapStats): void {
    console.log('📊 [RouteStepsComponent] Estatísticas do mapa atualizadas:', stats);
    this.mapStats = stats;
    this.cdr.detectChanges();
  }

  // ========================================
  // 🎯 MÉTODOS HELPER PARA O TEMPLATE
  // ========================================

  trackByStepId(index: number, step: RouteStep): string {
    return step.id;
  }

  getStepStatusClass(status: RouteStep['status']): string {
    const statusClasses = {
      'pending': 'pending',
      'completed': 'completed', 
      'failed': 'failed',
      'skipped': 'skipped'
    };
    return statusClasses[status] || 'pending';
  }

  getStepIcon(type: RouteStep['type']): string {
    const typeIcons = {
      'pickup': 'fas fa-box',
      'delivery': 'fas fa-truck',
      'rest': 'fas fa-coffee',
      'fuel': 'fas fa-gas-pump'
    };
    return typeIcons[type] || 'fas fa-circle';
  }

  getStepTitle(type: RouteStep['type']): string {
    const typeTitles = {
      'pickup': 'Coleta',
      'delivery': 'Entrega',
      'rest': 'Parada',
      'fuel': 'Combustível'
    };
    return typeTitles[type] || 'Etapa';
  }

  getStepLocationName(step: RouteStep): string {
    // Extrai nome da instalação ou usa primeira parte do endereço
    if (step.location.facility) {
      return step.location.facility;
    }
    
    // Pega primeira parte do endereço antes da vírgula
    const addressParts = step.location.address.split(',');
    return addressParts[0] || 'Local';
  }

  getStatusIcon(status: RouteStep['status']): string {
    const statusIcons = {
      'pending': 'fas fa-clock',
      'completed': 'fas fa-check-circle',
      'failed': 'fas fa-times-circle',
      'skipped': 'fas fa-forward'
    };
    return statusIcons[status] || 'fas fa-clock';
  }

  getStatusColor(status: RouteStep['status']): string {
    const statusColors = {
      'pending': '#6b7280',
      'completed': '#10b981',
      'failed': '#ef4444',
      'skipped': '#f59e0b'
    };
    return statusColors[status] || '#6b7280';
  }

  getStatusLabel(status: RouteStep['status']): string {
    const statusLabels = {
      'pending': 'Pendente',
      'completed': 'Completada',
      'failed': 'Falhada',
      'skipped': 'Pulada'
    };
    return statusLabels[status] || 'Pendente';
  }

  // ========================================
  // 🎯 MÉTODOS PARA ESTATÍSTICAS
  // ========================================

  getCompletedStepsCount(): number {
    return this.routeSteps.filter(step => step.status === 'completed').length;
  }

  getTotalEstimatedTime(): number {
    return this.routeSteps.reduce((total, step) => {
      return total + (step.estimatedDuration || 0);
    }, 0);
  }

  getProgressPercentage(): number {
    if (this.routeSteps.length === 0) {
      return 0;
    }
    const completed = this.getCompletedStepsCount();
    return Math.round((completed / this.routeSteps.length) * 100);
  }
} 