/**
 * 📍 RouteStopsComponent - Container Principal
 * 
 * Componente responsável por coordenar todos os sub-componentes do módulo
 * de paradas de rotas: mapa, lista lateral, formulário e modal de documentos.
 * 
 * ✨ Funcionalidades:
 * - Gerencia estado geral das paradas
 * - Coordena comunicação entre componentes
 * - Integra com RouteLocationTrackerComponent existente
 * - Controla modal de documentos fiscais
 * - Integração com sistema de rastreamento GPS
 */

import { Component, Input, OnInit, OnDestroy, ChangeDetectorRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BehaviorSubject, Subject, takeUntil, finalize } from 'rxjs';

import { RouteStop, RouteStopsFilters } from '../route-stops.interface';
import { RouteStopsService } from './route-stops.service';
import { RouteMapComponent } from './components/route-map/route-map.component';

// GPS Tracking
import { VehicleGpsTrackService } from './services/vehicle-gps-track.service';
import { GpsTrackPoint } from './interfaces/vehicle-gps.interface';

@Component({
  selector: 'app-route-stops',
  standalone: true,
  imports: [CommonModule, FormsModule, RouteMapComponent],
  
  templateUrl: './route-stops.component.html',
  styleUrl: './route-stops.component.scss'
})
export class RouteStopsComponent implements OnInit, OnDestroy {
  @Input() initialData: any;
  @ViewChild('routeMap') routeMapComponent!: RouteMapComponent;

  // ========================================
  // 🎯 PROPRIEDADES REATIVAS
  // ========================================
  
  private routeStopsSubject = new BehaviorSubject<RouteStop[]>([]);
  private loadingSubject = new BehaviorSubject<boolean>(false);
  private onlineSubject = new BehaviorSubject<boolean>(navigator.onLine);
  private fallbackSubject = new BehaviorSubject<boolean>(false);
  private selectedStopSubject = new BehaviorSubject<RouteStop | null>(null);
  private formVisibleSubject = new BehaviorSubject<boolean>(false);
  private formModeSubject = new BehaviorSubject<'create' | 'edit'>('create');
  private reconnectingSubject = new BehaviorSubject<boolean>(false);
  
  // 📍 GPS Tracking - Substituindo dados mockados
  private vehicleGpsTrackSubject = new BehaviorSubject<GpsTrackPoint[]>([]);
  private currentGpsPositionSubject = new BehaviorSubject<GpsTrackPoint | null>(null);
  
  private destroy$ = new Subject<void>();

  // ========================================
  // 🗺️ CONFIGURAÇÕES DO MAPA
  // ========================================
  
  showGpsTrack = true;
  showPlannedRoute = true;
  showCurrentRoute = true;
  currentRouteOrigin = 'São Paulo, SP';
  currentRouteDestination = 'Campinas, SP';
  
  // 📝 Propriedades para o painel de detalhes
  showDetailsPanel = false;

  // ========================================
  // 🎯 GETTERS PARA O TEMPLATE
  // ========================================
  
  get routeStops(): RouteStop[] {
    return this.routeStopsSubject.value;
  }
  
  get isLoading(): boolean {
    const loading = this.loadingSubject.value;
    // Log apenas nas mudanças de estado
    if (this._lastLoggedLoadingState !== loading) {
      console.log('🔍 [DEBUG] isLoading MUDOU para:', loading);
      this._lastLoggedLoadingState = loading;
    }
    return loading;
  }
  
  private _lastLoggedLoadingState: boolean | undefined;
  
  get isOnline(): boolean {
    return this.onlineSubject.value;
  }
  
  get isUsingFallback(): boolean {
    return this.fallbackSubject.value;
  }
  
  get selectedRouteStop(): RouteStop | null {
    return this.selectedStopSubject.value;
  }
  
  get isFormVisible(): boolean {
    return this.formVisibleSubject.value;
  }
  
  get formMode(): 'create' | 'edit' {
    return this.formModeSubject.value;
  }
  
  get isReconnecting(): boolean {
    return this.reconnectingSubject.value;
  }
  
  get routeId(): string {
    return this.initialData?.routeId || 'route_1';
  }

  // 🚗 GPS Getters
  get vehicleGpsTrack(): { lat: number; lng: number; timestamp: Date }[] {
    // return this.vehicleGpsTrackSubject.value.map(point => ({
    //   lat: point.lat,
    //   lng: point.lng,
    //   timestamp: point.timestamp instanceof Date ? point.timestamp : new Date(point.timestamp)
    // })); 
    return this.vehicleGpsTrackSubject.value.map(point => ({
    lat: point.lat,
    lng: point.lng,
    timestamp: point.timestamp instanceof Date ? point.timestamp : new Date(point.timestamp)
  }));
  }

  get currentGpsPosition(): GpsTrackPoint | null {
    return this.currentGpsPositionSubject.value;
  }

  constructor(
    private routeStopsService: RouteStopsService,
    private vehicleGpsTrackService: VehicleGpsTrackService,
    private cdr: ChangeDetectorRef
  ) {
    console.log('🏗️ RouteStopsComponent - Construtor chamado');
    console.log('🏗️ [DEBUG] Loading inicial:', this.isLoading);
  }

  ngOnInit(): void {
    console.log('🚀 RouteStopsComponent - ngOnInit', {
      initialData: this.initialData
    });
    
    console.log('📋 [DEBUG] Estado inicial do loading no ngOnInit:', this.isLoading);
    console.log('📋 [DEBUG] LoadingSubject valor inicial:', this.loadingSubject.value);
    
    this.setupOnlineStatusListener();
    
    // 🎯 LOG antes de chamar loadRouteStops
    console.log('📋 [DEBUG] Prestes a chamar loadRouteStops()');
    this.loadRouteStops();
    
    this.loadVehicleGpsTrack();
    
    // 🎯 TIMEOUT DE SEGURANÇA: Força finalização do loading após 10 segundos
    setTimeout(() => {
      if (this.isLoading) {
        console.warn('⚠️ [DEBUG] Loading timeout - forçando finalização');
        this.loadingSubject.next(false);
        this.cdr.detectChanges();
      }
    }, 10000);
  }

  ngOnDestroy(): void {
    console.log('🔥 RouteStopsComponent - ngOnDestroy - Limpando recursos...');
    this.vehicleGpsTrackService.stopRealTimeSimulation();
    this.destroy$.next();
    this.destroy$.complete();
    console.log('✅ RouteStopsComponent - Recursos limpos');
  }

  // ========================================
  // 🔄 CARREGAMENTO DE DADOS
  // ========================================

  private loadRouteStops(): void {
    console.log('📋 [DEBUG] Carregando paradas da rota:', this.routeId);
    
    this.loadingSubject.next(true);
    console.log('📋 [DEBUG] Loading definido como TRUE');
    
    // 🕐 TIMESTAMP do início do loading
    const loadingStartTime = Date.now();
    
    // 🎯 FORÇAR routeId para route_1 (dados JSON disponíveis)
    const filters: RouteStopsFilters = {
      routeId: 'route_1',
      page: 1,
      limit: 500
    };
    
    console.log('📋 [DEBUG] Chamando service com filtros:', filters);
    
    this.routeStopsService.getRouteStops(filters)
      .pipe(
        takeUntil(this.destroy$),
        finalize(() => {
          // 🕐 DELAY MÍNIMO: Garantir que loading seja visível por pelo menos 1.5 segundos
          const loadingDuration = Date.now() - loadingStartTime;
          const minLoadingTime = 1500; // 1.5 segundos
          const remainingTime = Math.max(0, minLoadingTime - loadingDuration);
          
          console.log('📋 [DEBUG] Duração do loading:', loadingDuration + 'ms');
          console.log('📋 [DEBUG] Delay adicional necessário:', remainingTime + 'ms');
          
          setTimeout(() => {
            console.log('📋 [DEBUG] FINALIZE executado - definindo loading como FALSE');
            this.loadingSubject.next(false);
            this.cdr.detectChanges();
          }, remainingTime);
        })
      )
      .subscribe({
        next: (response) => {
          console.log('✅ [DEBUG] Paradas carregadas:', response);
          console.log('✅ [DEBUG] Número de paradas:', response.data?.length || 0);
          
          this.routeStopsSubject.next(response.data);
          this.onlineSubject.next(this.routeStopsService.isOnline);
          this.fallbackSubject.next(this.routeStopsService.isUsingFallback);
          
          console.log(`📊 [DEBUG] Total de paradas no subject: ${response.data.length}`);
          console.log(`📊 [DEBUG] Loading atual: ${this.isLoading}`);
        },
        error: (error) => {
          console.error('❌ [DEBUG] Erro ao carregar paradas:', error);
          console.log('❌ [DEBUG] Definindo array vazio como fallback');
          this.routeStopsSubject.next([]);
        }
      });
  }

  /**
   * 🚗 Carregar dados de rastreamento GPS do veículo
   */
  private loadVehicleGpsTrack(): void {
    console.log('🚗 Carregando dados de GPS da rota:', this.routeId);
    
    // Forçar para route_1 onde temos dados JSON
    const routeIdToLoad = 'route_1';
    
    this.vehicleGpsTrackService.getSimpleGpsPoints(routeIdToLoad)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (gpsPoints) => {
          console.log('✅ Dados GPS carregados:', gpsPoints);
          this.vehicleGpsTrackSubject.next(gpsPoints);
          
          // ⚠️ REMOVIDO: NÃO definir posição atual automaticamente
          // Deixar que o usuário inicie a simulação manualmente
          console.log('📍 Dados GPS prontos para uso. Use os botões para controlar a simulação.');
        },
        error: (error) => {
          console.error('❌ Erro ao carregar dados GPS:', error);
          this.vehicleGpsTrackSubject.next([]);
        }
      });
  }

  private setupOnlineStatusListener(): void {
    window.addEventListener('online', () => {
      this.onlineSubject.next(true);
      this.cdr.detectChanges();
    });
    
    window.addEventListener('offline', () => {
      this.onlineSubject.next(false);
      this.cdr.detectChanges();
    });
  }

  // ========================================
  // 🎯 MÉTODOS DE INTERAÇÃO
  // ========================================

  onStopSelected(stop: RouteStop): void {
    console.log('📍 Parada selecionada:', stop);
    this.selectedStopSubject.next(stop);
    this.formVisibleSubject.next(false);
  }

  onStopEdit(stop: RouteStop): void {
    console.log('✏️ Editando parada:', stop);
    this.selectedStopSubject.next(stop);
    this.formModeSubject.next('edit');
    this.formVisibleSubject.next(true);
  }

  onStopDelete(stop: RouteStop): void {
    console.log('🗑️ Excluindo parada:', stop);
    
    if (confirm(`Deseja realmente excluir a parada "${stop.location.address}"?`)) {
      const currentStops = this.routeStopsSubject.value;
      const updatedStops = currentStops.filter(s => s.id !== stop.id);
      this.routeStopsSubject.next(updatedStops);
      
      if (this.selectedRouteStop?.id === stop.id) {
        this.selectedStopSubject.next(null);
      }
    }
  }

  onNewStopClick(): void {
    console.log('➕ Nova parada');
    this.selectedStopSubject.next(null);
    this.formModeSubject.next('create');
    this.formVisibleSubject.next(true);
  }

  onMapStopClick(stop: RouteStop): void {
    console.log('🗺️ Pin do mapa clicado:', stop);
    this.onStopSelected(stop);
  }

  onMapReady(isReady: boolean): void {
    console.log('🗺️ Mapa pronto:', isReady);
    
    if (isReady && this.routeMapComponent) {
      setTimeout(() => {
        console.log('🔄 Forçando redimensionamento do mapa...');
        this.routeMapComponent.forceMapFit();
      }, 500);
    }
  }

  onCurrentRouteCalculated(routeData: any): void {
    console.log('🌍 Rota atual calculada:', routeData);
    
    if (routeData && routeData.routes && routeData.routes.length > 0) {
      const route = routeData.routes[0];
      const totalDistance = route.legs?.reduce((sum: number, leg: any) => sum + leg.distance.value, 0) || 0;
      const totalDuration = route.legs?.reduce((sum: number, leg: any) => sum + leg.duration.value, 0) || 0;
      
      console.log(`📊 Rota atual: ${this.formatDistance(totalDistance)} em ${this.formatDuration(totalDuration)}`);
    }
  }

  onRouteInputChange(): void {
    console.log('🌍 Dados da rota alterados:', this.currentRouteOrigin, '→', this.currentRouteDestination);
  }

  onCalculateCurrentRoute(): void {
    console.log('🚀 Forçando cálculo da rota atual');
    
    if (!this.currentRouteOrigin.trim() || !this.currentRouteDestination.trim()) {
      alert('Por favor, informe origem e destino para calcular a rota.');
      return;
    }
    
    if (this.routeMapComponent) {
      this.routeMapComponent.reloadMap();
    }
  }

  // ========================================
  // 🚗 MÉTODOS GPS - SIMULAÇÃO E CONTROLE
  // ========================================

  /**
   * 🎬 Iniciar simulação GPS em tempo real
   */
  onStartGpsSimulation(): void {
    console.log('🎬 Iniciando simulação GPS...');
    
    const routeIdToSimulate = 'route_1'; // Usar dados disponíveis
    
    this.vehicleGpsTrackService.startRealTimeSimulation(routeIdToSimulate)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (firstPoint) => {
          console.log('🎬 Simulação iniciada no ponto:', firstPoint);
          this.currentGpsPositionSubject.next(firstPoint);
          
          // Subscrever aos updates da simulação
          this.subscribeToGpsSimulation();
        },
        error: (error) => {
          console.error('❌ Erro ao iniciar simulação GPS:', error);
          alert('Erro ao iniciar simulação GPS. Verifique se há dados disponíveis.');
        }
      });
  }

  /**
   * ⏸️ Parar simulação GPS
   */
  onStopGpsSimulation(): void {
    console.log('⏸️ Parando simulação GPS...');
    this.vehicleGpsTrackService.stopRealTimeSimulation();
  }

  /**
   * 📡 Subscrever aos updates da simulação em tempo real
   */
  private subscribeToGpsSimulation(): void {
    this.vehicleGpsTrackService.getRealTimeSimulation()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (gpsPoint) => {
          if (gpsPoint) {
            console.log('📡 Nova posição GPS:', gpsPoint);
            this.currentGpsPositionSubject.next(gpsPoint);
          } else {
            console.log('🏁 Simulação GPS finalizada');
          }
        },
        error: (error) => {
          console.error('❌ Erro na simulação GPS:', error);
        }
      });
  }

  /**
   * 📊 Verificar se simulação está rodando
   */
  get isGpsSimulationRunning(): boolean {
    return this.vehicleGpsTrackService.isSimulationRunningSyncronous;
  }

  private formatDistance(distanceInMeters: number): string {
    if (distanceInMeters > 1000) {
      return `${(distanceInMeters / 1000).toFixed(1)} km`;
    }
    return `${distanceInMeters} m`;
  }

  private formatDuration(durationInSeconds: number): string {
    const hours = Math.floor(durationInSeconds / 3600);
    const minutes = Math.floor((durationInSeconds % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}h ${minutes}min`;
    }
    return `${minutes}min`;
  }

  onMapAreaClick(coordinates: { lat: number; lng: number }): void {
    console.log('🗺️ Área do mapa clicada:', coordinates);
  }

  onAddFiscalDocument(stopId: string): void {
    console.log('📄 Adicionando documento fiscal para parada:', stopId);
  }

  onFormCancel(): void {
    console.log('❌ Cancelando formulário');
    this.formVisibleSubject.next(false);
    this.selectedStopSubject.next(null);
  }

  onReconnectClick(): void {
    if (this.isReconnecting) return;
    
    console.log('🔄 Tentando reconectar...');
    this.reconnectingSubject.next(true);
    
    setTimeout(() => {
      this.loadRouteStops();
      this.loadVehicleGpsTrack();
      this.reconnectingSubject.next(false);
    }, 2000);
  }

  getStopsWithFiscalDocuments(): number {
    return this.routeStops.filter(stop => stop.fiscalDocument).length;
  }

  // ========================================
  // 🎛️ CONTROLES DE VISUALIZAÇÃO DAS ROTAS
  // ========================================

  onTogglePlannedRoute(): void {
    this.showPlannedRoute = !this.showPlannedRoute;
    console.log('🔵 Toggle Rota Planejada:', this.showPlannedRoute);
    
    if (this.routeMapComponent) {
      this.routeMapComponent.togglePlannedRouteVisibility();
    }
  }

  onToggleGpsTrack(): void {
    this.showGpsTrack = !this.showGpsTrack;
    console.log('🔴 Toggle Rastreamento GPS:', this.showGpsTrack);
    
    if (this.routeMapComponent) {
      this.routeMapComponent.toggleGpsTrackVisibility();
    }
  }

  onToggleCurrentRoute(): void {
    this.showCurrentRoute = !this.showCurrentRoute;
    console.log('🟢 Toggle Rota Atual:', this.showCurrentRoute);
    
    if (this.routeMapComponent) {
      this.routeMapComponent.toggleCurrentRouteVisibility();
    }
  }

  // ========================================
  // 🏷️ MÉTODOS DE FORMATAÇÃO PARA O TEMPLATE
  // ========================================

  getTypeLabel(type: RouteStop['type']): string {
    const labels = {
      pickup: 'Coleta',
      delivery: 'Entrega',
      rest: 'Descanso',
      fuel: 'Combustível'
    };
    return labels[type] || type;
  }

  getStatusLabel(status: RouteStop['status']): string {
    const labels = {
      pending: 'Pendente',
      completed: 'Concluída',
      failed: 'Falhada',
      skipped: 'Pulada'
    };
    return labels[status] || status;
  }

  toggleDetailsPanel(): void {
    this.showDetailsPanel = !this.showDetailsPanel;
    console.log('📝 Toggle painel de detalhes:', this.showDetailsPanel);
  }
} 