import { Component, Input, OnInit, ChangeDetectorRef } from '@angular/core';
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
import { Observable, BehaviorSubject, switchMap, tap, catchError, of } from 'rxjs';

import { TollparkingService } from '../../../tollparking/tollparking.service';
import { Tollparking } from '../../../tollparking/tollparking.interface';
import { Vehicle } from '../../vehicle.interface';
import { DataTableComponent, Column } from '../../../../shared/components/data-table/data-table.component';

@Component({
  selector: 'app-vehicle-tollparking',
  standalone: true,
  imports: [CommonModule, DataTableComponent],
  providers: [CurrencyPipe, DatePipe],
  templateUrl: './vehicle-tollparking.component.html',
  styleUrl: './vehicle-tollparking.component.scss'
})
export class VehicleTollParkingComponent implements OnInit {
  @Input() vehicleData: Vehicle | undefined;
  tollparkingRecords$: Observable<Tollparking[]>;
  loading = false;
  hasError = false;
  
  private licensePlateSubject = new BehaviorSubject<string[] | null>(null);
  private _initialData: string[] | undefined;
  
  @Input() set initialData(data: string[] | undefined) {
    this._initialData = data;
  }

  columns: Column[] = [
    { 
      field: "id", 
      header: "ID", 
      sortable: true, 
      filterable: false,
      width: "80px"
    },
    { 
      field: "code", 
      header: "Código", 
      sortable: true, 
      filterable: false,
      width: "120px"
    },
    { 
      field: "description", 
      header: "Descrição", 
      sortable: true, 
      filterable: false 
    },
    {
      field: "date",
      header: "Data",
      sortable: true,
      filterable: false,
      width: "130px",
      label: (date: string) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
    },
    {
      field: "value",
      header: "Valor",
      sortable: true,
      filterable: false,
      width: "120px",
      label: (value: number) => this.currencyPipe.transform(value, 'BRL', 'symbol', '1.2-2') || "-"
    },
    { 
      field: "license_plate", 
      header: "Placa", 
      sortable: true, 
      filterable: false,
      width: "110px"
    },
    { 
      field: "driver_name", 
      header: "Motorista", 
      sortable: true, 
      filterable: false,
      label: (driver: string) => driver || "Não informado"
    },
    {
      field: "routeNumber",
      header: "Rota",
      sortable: true,
      filterable: false,
      label: (routeNumber: string) => routeNumber || "Não informado"
    }
  ];

  constructor(
    private tollparkingService: TollparkingService,
    private currencyPipe: CurrencyPipe,
    private datePipe: DatePipe,
    private cdr: ChangeDetectorRef
  ) {
    
    this.tollparkingRecords$ = this.licensePlateSubject.pipe(
      switchMap(licensePlates => {        
        if (!licensePlates || licensePlates.length === 0) {
          return of([]);
        }

        this.loading = true;
        this.hasError = false;
        this.cdr.detectChanges();

        return this.tollparkingService.getTollparkingByVehicle(licensePlates).pipe(
          tap((records) => {
            this.loading = false;
            this.hasError = false;
          }),
          catchError(error => {
            console.error('Erro ao carregar pedágios/estacionamento:', error);
            this.loading = false;
            this.hasError = true;
            this.cdr.detectChanges();
            return of([]);
          })
        );
      })
    );
  }

  ngOnInit(): void {
    // Use the array of license plates directly
    this.licensePlateSubject.next(this._initialData || null);
  }

  getTotalValue(records: Tollparking[]): number {
    if (!records?.length) return 0;
    
    return records.reduce((sum, record) => {
      const value = parseFloat(record.value?.toString() || '0') || 0;
      return sum + value;
    }, 0);
  }

  getRecordCount(records: Tollparking[]): number {
    return records ? records.length : 0;
  }

  getLastRecord(records: Tollparking[]): Tollparking | null {
    if (!records || records.length === 0) return null;
    return records.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0];
  }

  retryLoad(): void {
    this.licensePlateSubject.next(this._initialData || null);
  }
} 