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

import { DevicetrackerService } from '../../../devicetracker/devicetracker.service';
import { Devicetracker } from '../../../devicetracker/devicetracker.interface';
import { Vehicle } from '../../vehicle.interface';
import { DataTableComponent, Column } from '../../../../shared/components/data-table/data-table.component';
import { PaginatedResponse } from '../../../../shared/interfaces/paginate.interface';

@Component({
  selector: 'app-vehicle-devicetracker',
  standalone: true,
  imports: [CommonModule, DataTableComponent],
  providers: [DatePipe],
  templateUrl: './vehicle-devicetracker.component.html',
  styleUrl: './vehicle-devicetracker.component.scss'
})
export class VehicleDevicetrackerComponent implements OnInit {
  @Input() vehicleData: Vehicle | undefined;
  devicetrackerRecords$: Observable<Devicetracker[]>;
  loading = false;
  hasError = false;
  
  private vehicleIdSubject = new BehaviorSubject<number | null>(null);
  private _initialData: Vehicle | undefined;
  
  @Input() set initialData(data: Vehicle | undefined) {
    this._initialData = data;
    if (data?.id) {
      this.vehicleIdSubject.next(data.id);
    }
  }

  columns: Column[] = [
    { 
      field: "id", 
      header: "ID", 
      sortable: true, 
      filterable: false,
      width: "80px"
    },
    { 
      field: "imei", 
      header: "IMEI", 
      sortable: true, 
      filterable: false,
      width: "140px"
    },
    { 
      field: "model", 
      header: "Modelo", 
      sortable: true, 
      filterable: false 
    },
    { 
      field: "brand", 
      header: "Marca", 
      sortable: true, 
      filterable: false,
      width: "120px"
    },
    {
      field: "status",
      header: "Status",
      sortable: true,
      filterable: false,
      allowHtml: true,
      width: "100px",
      label: (value: any) => {
        const statusConfig: { [key: string]: { label: string, class: string } } = {
          'active': { label: 'Ativo', class: 'status-active' },
          'inactive': { label: 'Inativo', class: 'status-inactive' }
        };
        const config = statusConfig[value?.toLowerCase()] || { label: value, class: 'status-unknown' };
        return `<span class="status-badge ${config.class}">${config.label}</span>`;
      }
    },
    {
      field: "installedAt",
      header: "Instalação",
      sortable: true,
      filterable: false,
      width: "130px",
      label: (date: string) => this.datePipe.transform(date, "dd/MM/yyyy") || "-"
    },
    {
      field: "lastUpdateAt",
      header: "Última Atualização",
      sortable: true,
      filterable: false,
      width: "150px",
      label: (date: string) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
    },
    { 
      field: "gpsSignal", 
      header: "Sinal GPS", 
      sortable: true, 
      filterable: false,
      width: "100px",
      label: (signal: string) => signal || "Sem sinal"
    }
  ];

  constructor(
    private devicetrackerService: DevicetrackerService,
    private datePipe: DatePipe,
    private cdr: ChangeDetectorRef
  ) {
    
    this.devicetrackerRecords$ = this.vehicleIdSubject.pipe(
      switchMap(vehicleId => {        
        if (!vehicleId) {
          return of([]);
        }

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

        // 🎯 Filtrar rastreadores por veículo
        return this.devicetrackerService.getDevicetrackers(1, 100, { vehicleIds: vehicleId.toString() }).pipe(
          map((response: PaginatedResponse<Devicetracker>) => response?.data || []), // Extrair dados da resposta paginada
          tap(() => {
            this.loading = false;
            this.cdr.detectChanges();
          }),
          catchError(error => {
            console.error('Erro ao carregar rastreadores:', error);
            this.loading = false;
            this.hasError = true;
            this.cdr.detectChanges();
            return of([]);
          })
        );
      })
    );
  }

  ngOnInit() {
    if (this._initialData?.id) {
      this.vehicleIdSubject.next(this._initialData.id);
    }
  }

  retryLoad() {
    if (this._initialData?.id) {
      this.hasError = false;
      this.vehicleIdSubject.next(this._initialData.id);
    }
  }

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

  getActiveDevices(records: Devicetracker[]): Devicetracker[] {
    return records?.filter(record => record.status === 'active') || [];
  }

  getLastUpdate(records: Devicetracker[]): Devicetracker | null {
    if (!records?.length) return null;
    
    return records.reduce((latest, current) => {
      const latestDate = new Date(latest.lastUpdateAt || 0);
      const currentDate = new Date(current.lastUpdateAt || 0);
      return currentDate > latestDate ? current : latest;
    });
  }
} 