import { Injectable } from '@angular/core';
import { Observable, map, tap, catchError, of } from 'rxjs';
import { Papa } from 'ngx-papaparse';
import { ApiClientService } from '../../shared/services/api/api-client.service';
import { Tollparking } from './tollparking.interface';
import { PaginatedResponse } from '../../shared/interfaces/paginate.interface';
import { DomainService } from '../../shared/components/base-domain/base-domain.component';

@Injectable({
  providedIn: 'root'
})
export class TollparkingService implements DomainService<Tollparking> {
  
  constructor(
    private apiClient: ApiClientService,
    private papa: Papa
  ) {}

  getTollparkings(
    page = 1,
    limit = 10,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<Tollparking>> {
    
    let url = `vehicle-toll-parking?page=${page}&limit=${limit}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
          console.log(`🔧 [getTollparkings] Adicionando filtro: ${key} = ${value}`);
        }
      }
      
      if (params.toString()) {
        url += `&${params.toString()}`;
      }
    }
    
    console.log(`🌐 [getTollparkings] URL final da requisição: ${url}`);
    
    return this.apiClient.get<PaginatedResponse<Tollparking>>(url);
  }

  /**
   * Busca um tollparking específico por ID
   */
  getById(id: string | number): Observable<Tollparking> {
    return this.apiClient.get<Tollparking>(`vehicle-toll-parking/${id}`);
  }

  /**
   * Remove um tollparking
   */
  delete(id: string | number): Observable<void> {
    return this.apiClient.delete<void>(`/${id}`);
  }

  // ========================================
  // 🎯 MÉTODOS ESPERADOS PELO BaseDomainComponent
  // ========================================
  
  /**
   * ✅ Método genérico para listar - chamado automaticamente pelo BaseDomainComponent
   */
  getEntities(page: number, pageSize: number, filters: any): Observable<{
    data: Tollparking[];
    totalCount: number;
    pageCount: number;
    currentPage: number;
  }> {
    return this.getTollparkings(page, pageSize, filters).pipe(
      map(response => ({
        data: response.data,
        totalCount: response.totalCount,
        pageCount: response.pageCount,
        currentPage: response.currentPage
      }))
    );
  }

  /**
   * ✅ Método genérico para criar - chamado automaticamente pelo BaseDomainComponent
   */
  create(data: any): Observable<Tollparking> {
    return this.apiClient.post<Tollparking>('vehicle-toll-parking', data);
  }

  /**
   * ✅ Método genérico para atualizar - chamado automaticamente pelo BaseDomainComponent
   */
  update(id: any, data: any): Observable<Tollparking> {
    return this.apiClient.patch<Tollparking>(`vehicle-toll-parking/${id}`, data);
  }

  // ========================================
  // 🎯 MÉTODOS ESPECÍFICOS PARA VEÍCULOS
  // ========================================

  /**
   * Busca registros de pedágios/estacionamento por veículos (placas)
   * @param licensePlates - Array de placas dos veículos
   * @returns Observable com array de registros de tollparking  
   */
  getTollparkingByVehicle(licensePlates: string[], dateFilters?: {start_date: string, end_date: string} | undefined): Observable<Tollparking[]> {
    // Converter array para string separada por vírgulas para o filtro
    const plateFilter = licensePlates.join(',');
    const filters: { license_plates: string, start_date?: string, end_date?: string } = { 'license_plates': plateFilter };
    if (dateFilters) {
      filters['start_date'] = dateFilters.start_date;
      filters['end_date'] = dateFilters.end_date;
    }
    
    console.log(`🔍 [TollparkingService] Buscando registros para placas:`, licensePlates);
    console.log(`📋 [TollparkingService] Filtros aplicados:`, filters);
    
    return this.getTollparkings(1, 100, filters).pipe(
      map(response => response.data || []),
      tap(records => {
        console.log(`✅ [TollparkingService] Carregados ${records.length} registros para placas:`, licensePlates);
        if (records.length > 0) {
          const uniquePlates = [...new Set(records.map(r => r.license_plate))];
          console.log(`📊 [TollparkingService] Placas encontradas nos registros:`, uniquePlates);
          const expectedPlates = new Set(licensePlates);
          const foundUnexpected = uniquePlates.some(plate => !expectedPlates.has(plate));
          if (foundUnexpected) {
            console.warn(`⚠️ [TollparkingService] ATENÇÃO: Filtro pode não estar funcionando! Esperado:`, licensePlates, 'Encontrado:', uniquePlates);
          }
        }
      }),
      catchError(error => {
        console.error('❌ Error loading tollparking records for vehicles:', error);
        return of([]);
      })
    );
  }

  /**
   * Busca estatísticas de pedágios/estacionamento por veículo
   * @param licensePlate - Placa do veículo
   * @returns Observable com estatísticas consolidadas
   */
  getTollparkingStatsByVehicle(licensePlate: string): Observable<{
    totalRecords: number;
    totalValue: number;
    lastRecord?: Tollparking;
    averageValue: number;
    recordsThisMonth: number;
    valueThisMonth: number;
  }> {
    return this.getTollparkingByVehicle([licensePlate]).pipe(
      map(records => {
        const now = new Date();
        const currentMonth = now.getMonth();
        const currentYear = now.getFullYear();
        
        const recordsThisMonth = records.filter(record => {
          const recordDate = new Date(record.date);
          return recordDate.getMonth() === currentMonth && 
                 recordDate.getFullYear() === currentYear;
        });
        
        const totalValue = records.reduce((sum, record) => sum + (record.value || 0), 0);
        const valueThisMonth = recordsThisMonth.reduce((sum, record) => sum + (record.value || 0), 0);
        const lastRecord = records.sort((a, b) => 
          new Date(b.date).getTime() - new Date(a.date).getTime()
        )[0];
        
        return {
          totalRecords: records.length,
          totalValue,
          lastRecord,
          averageValue: records.length > 0 ? totalValue / records.length : 0,
          recordsThisMonth: recordsThisMonth.length,
          valueThisMonth
        };
      })
    );
  }


  // ========================================
  // 🎯 MÉTODOS DASHBOARD
  // ========================================
  getTollparkingsDashboardList(
    page = 1,
    limit = 10,
    filters?: {[key: string]: string}
  ): Observable<PaginatedResponse<Tollparking>> {
    
    let url = `vehicle-toll-parking/dashboard/list?page=${page}&limit=${limit}`;
    
    if (filters) {
      const params = new URLSearchParams();
      
      for (const [key, value] of Object.entries(filters)) {
        if (value) {
          params.append(key, value);
          console.log(`🔧 [getTollparkings] Adicionando filtro: ${key} = ${value}`);
        }
      }
      
      if (params.toString()) {
        url += `&${params.toString()}`;
      }
    }
    
    console.log(`🌐 [getTollparkings] URL final da requisição: ${url}`);
    
    return this.apiClient.get<PaginatedResponse<Tollparking>>(url);
  }

}