import { Component, ChangeDetectorRef } from "@angular/core";
import { CommonModule, DatePipe } from "@angular/common";

import { TitleService } from "../../shared/services/theme/title.service";
import { HeaderActionsService } from "../../shared/services/header-actions.service";
import { DevicetrackerService } from "./devicetracker.service";
import { Devicetracker } from "./devicetracker.interface";

import { TabSystemComponent } from "../../shared/components/tab-system/tab-system.component";
import { BaseDomainComponent, DomainConfig } from "../../shared/components/base-domain/base-domain.component";
import { TabFormConfig } from "../../shared/interfaces/generic-tab-form.interface";
import { TabFormConfigService } from "../../shared/components/tab-system/services/tab-form-config.service";
import {VehiclesService} from "../vehicles/vehicles.service";
import { PersonService } from "../../shared/services/person.service";


/**
 * 🎯 DevicetrackerComponent - Gestão de Rastreadores
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-devicetracker',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './devicetracker.component.html',
  styleUrl: './devicetracker.component.scss'
})
export class DevicetrackerComponent extends BaseDomainComponent<Devicetracker> {

  constructor(
    private devicetrackerService: DevicetrackerService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService,
    private vehiclesService: VehiclesService,
    private personService: PersonService // ✅ Injeção do PersonService para remote-select
  ) {
    super(titleService, headerActionsService, cdr, devicetrackerService);
    this.registerFormConfig();
  }

  private registerFormConfig(): void {
    this.tabFormConfigService.registerFormConfig('devicetracker', () => this.getFormConfig());
  }

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'devicetracker',
      title: 'Rastreadores',
      entityName: 'Rastreador',
      pageSize: 50,
      subTabs: ['dados','vehicle','chip','instalation','advanced'],
      columns: [
        {field: "id", header: "Id", sortable: true, filterable: true, search: true, searchType: "number" },
        {field: "vehiclePlate", header: "Placa", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "imei", header: "IMEI", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "vehiclePlate", header: "Placa", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "vehicleModel", header: "Veículo Modelo", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "model", header: "Modelo", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "brand", header: "Marca", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "osVersion", header: "Versão do Sistema", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "simOperatorName", header: "Operadora do SIM", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "simCountry", header: "País do SIM", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "gpsSignal", header: "Sinal de GPS", sortable: true, filterable: true, search: true, searchType: "text"},
        {field: "installedAt", header: "Data de instalação", sortable: true, filterable: true, search: true, searchType: "date", label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-" },
        {field: "lastUpdateAt", header: "Última atualização", sortable: true, filterable: true, search: true, searchType: "date", label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-" },
        {
          field: "status",
          header: "Status",
          sortable: true,
          filterable: true,
          allowHtml: true,
          search: true,
          searchType: "select",
          searchOptions: [
            { value: 'active', label: 'Ativo' },
            { value: 'inactive', label: 'Inativo' }
          ],
          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: "createdAt",
          header: "Criado em",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
        },
        {
          field: "deviceId",
          header: "ID do Equipamento",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "text"
        }
      ],
      
      sideCard: {
        enabled: true,
        title: "Resumo do Rastreador",
        position: "right",
        width: "400px",
        component: "summary",
        data: {
          imageField: "photoIds",
          displayFields: [
            // {
            //   key: "personId",
            //   label: "Responsável pela Instalação",
            //   type: "text"
            // },
            {
              key: "status",
              label: "Status",
              type: "status"
            },
            {
              key: "createdAt",
              label: "Criado em",
              type: "date",
              format: (value: any) => this.datePipe.transform(value, "dd/MM/yyyy HH:mm") || "-"
            },
            {
              key: "locationLatitude",
              label: "Latitude",
              type: "text"
            },
            {
              key: "locationLongitude",
              label: "Longitude",
              type: "text"
            },
            {
              key: "batteryLevel",
              label: "Nível de bateria",
              type: "text"
            },
            {
              key: "gpsSignal",
              label: "Sinal de GPS",
              type: "text"
            }
          ],
          statusField: "status"
        }
      }
    };
  }

  getFormConfig(): TabFormConfig {
    return {
      title: 'Dados do Rastreador',
      entityType: 'devicetracker',
      fields: [],
      submitLabel: 'Salvar Dispositivo',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dispositivo (OBD)',
          icon: 'fa-info-circle',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['name'],
          fields: [
            {
              key: 'imei',
              label: 'IMEI',
              type: 'text',
              required: true,
              placeholder: 'Digite o IMEI'
            },
            {
              key: 'model',
              label: 'Modelo',
              type: 'text',
              required: true,
              placeholder: 'Digite o Modelo'
            },
            {
              key: 'deviceId',
              label: 'ID do Equipamento',
              type: 'text',
              required: true,
              placeholder: 'Digite o ID do dispositivo'
            },
            {
              key: 'brand',
              label: 'Marca',
              type: 'text',
              required: true,
              placeholder: 'Digite a Marca'
            },
            {
              key: 'osVersion',
              label: 'Versão do Sistema',
              type: 'text',
              required: true,
              placeholder: 'Digite a Versão do Sistema'
            },
            {
              key: 'role',
              label: 'Função',
              type: 'select',
              required: true,
              options: [
                { value: 'main', label: 'Principal' },
                { value: 'backup', label: 'Backup' }
              ]
            },
            {
              key: 'installedAt',
              label: 'Data de Instalação',
              type: 'date',
              required: true              
            },
            // {
            //   key:'personId',
            //   label: 'Responsável',
            //   type: 'remote-select',
            //   required: true,
            //   remoteConfig: {
            //     service: this.personService,
            //     searchField: 'name',
            //     displayField: 'name',
            //     valueField: 'id',
            //     modalTitle: 'Selecione a pessoa proprietária',
            //     placeholder: 'Digite o nome do proprietária...'
            //   }
            // },
            {
              key: 'lastUpdateAt',
              label: 'Última atualização',
              type: 'date',
              required: true,
              placeholder: 'Digite a Última atualização'
            },
          ]
        },
        //vehicle information
        {
          id: 'vehicle',
          label: 'Veículo',
          icon: 'fa-car',
          enabled: true,
          order: 4,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            // {
            //   key: 'locationPersonId',
            //   label: '',
            //   required: false,
            //   labelField: 'locationPersonName',
            //   type: 'remote-select',
            //   remoteConfig: {
            //     service: this.personService,
            //     searchField: 'name',
            //     displayField: 'name',
            //     valueField: 'id',
            //     modalTitle: 'Selecione o local de alocação',
            //     placeholder: 'Digite o nome do local de alocação...'
            //   }
            // },
            {
              key:'vehicleId',
              label: '',
              labelField: 'vehiclePlate', // ✅ Campo para mostrar o valor selecionado
              type: 'remote-select',
              required: false,
              remoteConfig: {
                service: this.vehiclesService,
                searchField: 'license_plate',
                displayField: 'license_plate',
                valueField: 'id',
                modalTitle: 'Selecione o veículo',
                placeholder: 'Digite a placa do veículo...'
              }
            },
            {
              key: 'status',
              label: 'Status do Veículo',
              type: 'select',
              required: true,
              options: [
                { value: 'active', label: 'Ativo' },
                { value: 'inactive', label: 'Inativo' }
              ]
            }
          ]
        },
      //chip information
        {
            id: 'chip',
            label: 'Informações do Chip',
            icon: 'fa-microchip',
            enabled: true,
            order: 4,
            templateType: 'fields',
            requiredFields: [],
            fields: [
              {
                key: 'simNumber',
                label: 'Número do SIM',
                type: 'text',
                required: true,
                placeholder: 'Digite o Número do SIM'
              },
              {
                key: 'simOperator',
                label: 'Fornecedora',
                type: 'text',
                required: true,
                placeholder: 'Digite a Operadora do SIM'
              },
              {
                key: 'simOperatorName',
                label: 'Operadora',
                type: 'text',
                required: true,
                placeholder: 'Digite a Operadora do SIM'
              },
              {
                key: 'simCountry',
                label: 'País',
                type: 'text',
                required: true,
                placeholder: 'Digite o País do SIM'
              },
              {
                key: 'simCountryCode',
                label: 'Código do País (DDI)',
                type: 'text',
                required: true,
                placeholder: 'Digite o Código do País do SIM'
              },
            ]
        },
        {
          id: 'instalation',
          label: 'Dados da Instalação',
          icon: 'fa-microchip',
          enabled: true,
          order: 4,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            {
              key: 'installedAt',
              label: 'Data de Instalação',
              type: 'date',
              required: true,
              placeholder: 'Digite a Data de Instalação'
            },
             {
              key:'installedBy',
              label: '',
              type: 'remote-select',
              required: false,
              remoteConfig: {
                service: this.personService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                modalTitle: 'Digite o Instalador',
                placeholder: 'instalado por...'
              }
            },
            {
              key: 'locationCity',
              label: 'Cidade',
              type: 'text',
              required: true,
              placeholder: 'Digite a Cidade'
            },
            { key: 'locationState',
              label: 'Estado',
              type: 'text',
              required: true,
              placeholder: 'Digite o Estado'
            },
            {
              key: 'locationAddress',
              label: 'Endereço',
              type: 'text',
              required: true,
              placeholder: 'Digite o Endereço'
            },
            {
              key: 'locationDateTime',
              label: 'Data e Hora da Leitura',
              type: 'date',
              required: true,
              placeholder: 'Digite a Data e Hora da Leitura'
            },
            ]
        },
        // {
        //   id: 'photos',
        //   label: 'Fotos do Dispositivo',
        //   icon: 'fa-camera',
        //   enabled: true,
        //   order: 2,
        //   templateType: 'fields',
        //   requiredFields: [],
        //   fields: [
        //     {
        //       key: 'photoIds',
        //       label: 'Fotos',
        //       type: 'send-image',
        //       required: false,
        //       imageConfiguration: {
        //         maxImages: 10,
        //         maxSizeMb: 5,
        //         allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
        //         existingImages: []
        //       }
        //     }
        //   ]
        // },
        {
          id: 'advanced',
          label: 'Detalhes',
          icon: 'fa-cogs',
          enabled: true,
          order: 4,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            {
              key: 'latitude',
              label: 'Latitude',
              type: 'number',
              required: false,
              placeholder: 'Digite a Latitude'
            },
            {
              key: 'longitude',
              label: 'Longitude',
              type: 'number',
              required: false,
              placeholder: 'Digite a Longitude'
            },
          
            {
              key: 'currentFuelPercent',
              label: 'Percentual de combustível atual',
              type: 'number',
              required: false,
              placeholder: 'Digite o Percentual de combustível atual'
            },
            {
              key: 'currentFuelLiters',
              label: 'Litros de combustível atual',
              type: 'number',
              required: false,
              placeholder: 'Digite quantos litros de combustível tem no veículo'
            },
            {
              key: 'totalFuelLiters',
              label: 'Litros de combustível total',
              type: 'number',
              required: false,
              placeholder: 'Digite quantos litros de combustível tem no veículo'
            },
            {
              key: 'currentTripKm',
              label: 'Km atual',
              type: 'number',
              required: false,
              placeholder: 'Digite a quilometragem atual'
            },
            {
              key: 'totalMileageKm',
              label: 'Quilometragem total',
              type: 'number',
              required: false,
              placeholder: 'Digite a quilometragem total'
            },
            {
              key: 'speedKmh',
              label: 'Velocidade',
              type: 'number',
              required: false,
              placeholder: 'Digite a velocidade'
            },
            {
              key: 'gpsSignal',
              label: 'Sinal de GPS',
              type: 'text',
              required: false,
              placeholder: 'Digite o Sinal de GPS'
            },
            {
              key: 'batteryLevel',
              label: 'Nível de bateria',
              type: 'number',
              required: false,
              placeholder: 'Digite o Nível de bateria'
            },
            // {
            //   key: 'driverId',
            //   label: 'Motorista',
            //   type: 'remote-select',
            //   remoteConfig: {
            //     service: this.vehiclesService,
            //     searchField: 'license_plate',
            //     displayField: 'license_plate',
            //     valueField: 'id',
            //     placeholder: 'Digite a placa do veículo...'
            //   }
            // }
          ]
        },
      ]
    };
  }

  protected override getNewEntityData(): Partial<Devicetracker> {
     const devicetracker: Partial<Devicetracker> =
     {
      name: '',
      imei: '',
      model: '',
      brand: '',
      osVersion: '',
      simNumber: '',
      simOperator: '',
      simOperatorName: '',
      simCountry: '',
      simCountryCode: '',
      locationCity: '',
      locationState: '',
      locationAddress: '',
      status: '',
      vehicleId: 0,
      role: '',
      installedAt: new Date(''),
      personId: 1,
      installedBy: '',
      initialMileageKm: 0,
      initialTripKm: 0,
      initialFuelLiters: 0,
    };
    console.log(devicetracker);
    return devicetracker;
  }
  

}