import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

import { RouteStep, RouteStepsFilter } from './route-steps.interface';
import { ApiClientService } from '../../../shared/services/api/api-client.service';
import { PaginatedResponse } from '../../../shared/interfaces/paginate.interface';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RouteStepsService {

  constructor(
    private apiClient: ApiClientService,
    private httpClient: HttpClient
  ) {}

  // ========================================
  // 🎯 MÉTODOS ESPECÍFICOS DO DOMÍNIO
  // ========================================

  getRouteSteps(
    routeId: string,
    filters?: RouteStepsFilter
  ): Observable<RouteStep[]> {
    
    let url = `routes/steps/${routeId}`;
        

    return this.apiClient.get<RouteStep[]>(url).pipe(
      catchError(error => {
        console.warn('⚠️ Backend indisponível, usando dados de fallback', error);
        
        return this.getFallbackData(routeId);

      })
    );
  }

  getById(stepId: string): Observable<RouteStep> {
    return this.apiClient.get<RouteStep>(`route-steps/${stepId}`).pipe(
      catchError(error => {
        console.warn('⚠️ Backend indisponível, usando dados de fallback', error);
        return this.getFallbackStepData(stepId);
      })
    );
  }

  create(routeId: string, data: Partial<RouteStep>): Observable<RouteStep> {
    return this.apiClient.post<RouteStep>(`routes/${routeId}/steps`, data);
  }

  update(stepId: string, data: Partial<RouteStep>): Observable<RouteStep> {
    return this.apiClient.patch<RouteStep>(`route-steps/${stepId}`, data);
  }

  delete(stepId: string): Observable<void> {
    return this.apiClient.delete<void>(`route-steps/${stepId}`);
  }

  updateStepStatus(stepId: string, status: RouteStep['status']): Observable<RouteStep> {
    return this.apiClient.patch<RouteStep>(`route-steps/${stepId}/status`, { status });
  }

  // ========================================
  // 🎯 DADOS DE FALLBACK
  // ========================================

  private getFallbackData(routeId: string): Observable<RouteStep[]> {

    console.log('📁 [RouteSteps] Carregando dados do arquivo: /assets/data/route-stops-data.json');
    
    return this.httpClient.get<RouteStep[]>('/assets/data/route-stops-data.json').pipe(
      map((data: RouteStep[]) => {
        const processedData = data.map(stop => ({
          ...stop,
          scheduledTime: new Date(stop.scheduledTime),
          actualTime: stop.actualTime ? new Date(stop.actualTime) : undefined,
          createdAt: new Date(stop.createdAt),
          updatedAt: new Date(stop.updatedAt),
          fiscalDocument: stop.fiscalDocument ? {
            ...stop.fiscalDocument,
            issueDate: new Date(stop.fiscalDocument.issueDate),
            createdAt: new Date(stop.fiscalDocument.createdAt),
            updatedAt: new Date(stop.fiscalDocument.updatedAt)
          } : undefined
        }));
        
        console.log('✅ [RouteSteps] Dados carregados do arquivo JSON:', processedData); 
        return processedData;
      }),
      catchError(error => {
        console.error('❌ [RouteStops] Erro ao carregar arquivo route-stops-data.json:', error);
        return of([]);
      })
    );

    // return {
    //   routeId: routeId,
    //   routeNumber: 'RT-2024-001',
    //   status: 'active',
    //   totalSteps: 5,
    //   completedSteps: 2,
    //   estimatedDuration: 240, // 4 horas
    //   actualDuration: 150, // 2.5 horas parcial
    //   driver: {
    //     id: 'driver_1',
    //     name: 'João Silva',
    //     photo: '/assets/imagens/driver.placeholder.svg'
    //   },
    //   vehicle: {
    //     id: 'vehicle_1',
    //     plate: 'ABC-1234',
    //     model: 'Mercedes Sprinter'
    //   },
    //   steps: [
    //     {
    //       id: 'step_1',
    //       stepNumber: 1,
    //       title: 'Coleta - Centro de Distribuição',
    //       description: 'Coleta de mercadorias no CD principal',
    //       status: 'completed',
    //       estimatedTime: 30,
    //       actualTime: 25,
    //       address: {
    //         street: 'Av. Paulista',
    //         number: '1000',
    //         city: 'São Paulo',
    //         state: 'SP',
    //         zipCode: '01310-100',
    //         coordinates: { lat: -23.5489, lng: -46.6388 }
    //       },
    //       type: 'pickup',
    //       priority: 'high',
    //       notes: 'Coleta realizada com sucesso',
    //       scheduledTime: '2024-01-15T08:00:00Z',
    //       completedTime: '2024-01-15T08:25:00Z',
    //       documents: {
    //         required: ['nota_fiscal', 'manifesto'],
    //         uploaded: ['nota_fiscal', 'manifesto']
    //       }
    //     },
    //     {
    //       id: 'step_2',
    //       stepNumber: 2,
    //       title: 'Entrega - Cliente A',
    //       description: 'Primeira entrega do dia',
    //       status: 'completed',
    //       estimatedTime: 45,
    //       actualTime: 40,
    //       address: {
    //         street: 'Rua Augusta',
    //         number: '500',
    //         city: 'São Paulo',
    //         state: 'SP',
    //         zipCode: '01304-000',
    //         coordinates: { lat: -23.5557, lng: -46.6631 }
    //       },
    //       type: 'delivery',
    //       priority: 'medium',
    //       contact: {
    //         name: 'Maria Santos',
    //         phone: '(11) 99999-1234',
    //         email: 'maria@clientea.com'
    //       },
    //       scheduledTime: '2024-01-15T09:00:00Z',
    //       completedTime: '2024-01-15T09:40:00Z',
    //       documents: {
    //         required: ['comprovante_entrega'],
    //         uploaded: ['comprovante_entrega']
    //       }
    //     },
    //     {
    //       id: 'step_3',
    //       stepNumber: 3,
    //       title: 'Entrega - Cliente B',
    //       description: 'Segunda entrega agendada',
    //       status: 'in-progress',
    //       estimatedTime: 40,
    //       address: {
    //         street: 'Av. Faria Lima',
    //         number: '1500',
    //         city: 'São Paulo',
    //         state: 'SP',
    //         zipCode: '01452-000',
    //         coordinates: { lat: -23.5781, lng: -46.6890 }
    //       },
    //       type: 'delivery',
    //       priority: 'high',
    //       contact: {
    //         name: 'Pedro Oliveira',
    //         phone: '(11) 88888-5678'
    //       },
    //       scheduledTime: '2024-01-15T10:30:00Z',
    //       documents: {
    //         required: ['comprovante_entrega'],
    //         uploaded: []
    //       }
    //     },
    //     {
    //       id: 'step_4',
    //       stepNumber: 4,
    //       title: 'Parada - Posto de Combustível',
    //       description: 'Abastecimento programado',
    //       status: 'pending',
    //       estimatedTime: 20,
    //       address: {
    //         street: 'Av. Rebouças',
    //         number: '800',
    //         city: 'São Paulo',
    //         state: 'SP',
    //         zipCode: '05402-000',
    //         coordinates: { lat: -23.5629, lng: -46.6711 }
    //       },
    //       type: 'rest',
    //       priority: 'low',
    //       scheduledTime: '2024-01-15T12:00:00Z',
    //       documents: {
    //         required: ['cupom_combustivel'],
    //         uploaded: []
    //       }
    //     },
    //     {
    //       id: 'step_5',
    //       stepNumber: 5,
    //       title: 'Retorno - Base',
    //       description: 'Retorno ao centro de distribuição',
    //       status: 'pending',
    //       estimatedTime: 45,
    //       address: {
    //         street: 'Av. Paulista',
    //         number: '1000',
    //         city: 'São Paulo',
    //         state: 'SP',
    //         zipCode: '01310-100',
    //         coordinates: { lat: -23.5489, lng: -46.6388 }
    //       },
    //       type: 'checkpoint',
    //       priority: 'medium',
    //       scheduledTime: '2024-01-15T14:00:00Z',
    //       documents: {
    //         required: ['relatorio_viagem'],
    //         uploaded: []
    //       }
    //     }
    //   ],
    //   createdAt: '2024-01-15T07:00:00Z',
    //   updatedAt: '2024-01-15T09:40:00Z'
    // };
  }

  private getFallbackStepData(stepId: string): Observable<RouteStep> {
    return this.getFallbackData('route_1').pipe(
      map(steps => steps.find(step => step.id === stepId) || steps[0] || {} as RouteStep)
    );
  }
} 