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 { DriverperformanceService } from "./driverperformance.service";
import { Driverperformance } from "./driverperformance.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 { DateRangeShortcuts } from "../../shared/utils/date-range.utils";
import { PersonService } from "../../shared/services/person.service";
/**
 * 🎯 DriverperformanceComponent - Gestão de Performance
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-driverperformance',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './driverperformance.component.html',
  styleUrl: './driverperformance.component.scss'
})
export class DriverperformanceComponent extends BaseDomainComponent<Driverperformance> {

  constructor(
    private driverperformanceService: DriverperformanceService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService,
    private personService: PersonService
  ) {
    super(titleService, headerActionsService, cdr, driverperformanceService);
    this.registerFormConfig();
  }

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

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'driverperformance',
      title: 'Performance',
      entityName: 'driverperformance',
      pageSize: 500,
      subTabs: ['dados','tollparking','abastecimento','fines'],
      filterConfig: {
        defaultFilters: [
          // {
          //   field: 'status',
          //   operator: 'in', 
          //   value: ['PENDING', 'INPROGRESS','DELIVERED', 'DELAYED', 'CANCELLED']
          // },
          {
            field: 'startDate',
            operator: 'gte',
            value:  DateRangeShortcuts.currentMonth().date_start
          },
          {
            field: 'endDate',
            operator: 'lte',
            value:  DateRangeShortcuts.currentMonth().date_end
          }
        ],
        fieldsSearchDefault: ['vehiclePlate'],
        dateRangeFilter: true,
        dateFieldNames: {
          startField: 'startDate',
          endField: 'endDate'
        },
        companyFilter: true,
        searchConfig: {
          minSearchLength: 4,           // ✨ Só pesquisar após 3 caracteres
          debounceTime: 400,           // ✨ Aguardar 500ms após parar de digitar
          preserveSearchOnDataChange: true  // ✨ Não apagar o campo quando dados chegam
        }
      },
      columns: [
        { 
          field: "driverName", 
          header: "Motorista", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "text" 
        },
        { 
          field: "vehiclePlates", 
          header: "Placa", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "text"
        },
        {
          field: "locationName",
          header: "Local de Alocação",
          sortable: true,
          filterable: true, 
          search: true,          
          searchType: "remote-select",
          searchField: "locationPersonId", // ✅ Campo para filtrar na API
          remoteConfig: { // ✅ NOVO: Configuração para remote-select
            label: '', // ✅ Label personalizado para o filtro
            service: this.personService,
            searchField: 'name',
            displayField: 'name',
            valueField: 'id',
            labelField: 'locationPersonId',
            modalTitle: 'Selecione os locais de alocação',
            placeholder: 'Digite o nome do local de alocação...',
            multiple: true, // ✅ SEMPRE múltiplo para filtros
            maxResults: 50 // ✅ Mais resultados para filtros
          },
          label: (value: any, row: any) => {
            if (!value) return 'Não atribuído';            
            return value;
          }
        },
        {           
          field: "qtyRoutes", 
          header: "Qtde de Rotas", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number" ,
          label: (value: any) => {
            if (!value) return '-';
            return `${Number(value).toLocaleString('pt-BR')} rotas`
          },
          footer: {
            type: 'sum',
            format: 'number',
            label: 'Total:',
            precision: 0
          }
        },
        { field: "totalVolume", 
          header: "Volume Total", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number",
          label: (value: any) => {
            if (!value) return '-';
            return `${Number(value).toLocaleString('pt-BR')} un.`
          },
          footer: {
            type: 'sum',
            format: 'number',
            label: 'Total:',
            precision: 0
          }

        },

        { field: "totalDistance",
           header: "Distância Total", 
           sortable: true, 
           filterable: true, 
           search: false, 
           searchType: "number",
           label: (value: any) => {
            if (!value) return '-';
            return `${Number(value).toLocaleString('pt-BR')} km`
          },
          footer: {
            type: 'sum',
            format: 'number',
            label: 'Total:', 
            precision: 0
          }
        },
        { 
          field: "totalToll", 
          header: "Total de Pedágio", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number",
          label: (value: any) => {
            if (!value) return '-';
            return `R$ ${Number(value).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;
          },
          footer: {
            type: 'sum',
            format: 'currency',
            label: 'Total:',
            precision: 2
          }
        },
        { field: "totalFine", 
          header: "Total de Multas", 
          sortable: true, 
          filterable: true, 
          search: false, 
          searchType: "number" 
        },
        { field: "totalAmbulance", header: "Total de Help", sortable: true, filterable: true, search: false, searchType: "number" },
        { field: "gasAmount", header: "Total de Combustível", sortable: true, filterable: true, search: false, searchType: "number" },
        { field: "companyName", header: "Empresa", sortable: true, filterable: true, search: false, searchType: "text" },
        // { field: "gasStationBrand", header: "Posto", sortable: true, filterable: true, search: true, searchType: "text" },
        // { field: "odometer", header: "Odômetro (Km)", sortable: true, filterable: true, search: true, searchType: "number" },        
        // {
        //   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") || "-"
        }
      ]
    };
  }

  getFormConfig(): TabFormConfig {
    return {
      title: 'Dados do Driverperformance',
      entityType: 'driverperformance',
      fields: [],
      submitLabel: 'Salvar Driverperformance',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-info-circle',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['name'],
          fields: [
            {
              key: 'name',
              label: 'Nome',
              type: 'text',
              required: true,
              placeholder: 'Digite o nome'
            },
            {
              key: 'status',
              label: 'Status',
              type: 'select',
              required: true,
              options: [
                { value: 'active', label: 'Ativo' },
                { value: 'inactive', label: 'Inativo' }
              ]
            }
          ]
        },
        {
          id: 'tollparking',
          label: 'Pedágios & Estacionamento',
          icon: 'fa-gas-pump',
          enabled: true,
          order: 7,
          templateType: 'component',
          dynamicComponent: {
            selector: 'app-vehicle-tollparking',
            inputs: {},
            dataBinding: { 
              getInitialData: () => this.getLicensePlatesFromData()
            }
          },
          requiredFields: []
        },
      ]
    };
  }
  getLicensePlatesFromData(): Driverperformance {
      return this.tabSystem?.getSelectedTab()?.data.vehiclePlates as Driverperformance;  
  }

  protected override getNewEntityData(): Partial<Driverperformance> {
    return {
      name: '',
      status: 'active',
      
      
    };
  }
}