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 { ContractService } from "./contract.service";
import { Contract } from "./contract.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 { PersonService } from "../person/person.service";
import { CompanyService } from "../company/company.service";
/**
 * 🎯 ContractComponent - Gestão de Contratos
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-contract',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './contract.component.html',
  styleUrl: './contract.component.scss'
})
export class ContractComponent extends BaseDomainComponent<Contract> {

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

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

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'contract',
      title: 'Contratos',
      entityName: 'Contrato',
      pageSize: 500,
      filterConfig: {
        fieldsSearchDefault: ['vehicleLicencePlates'],
        dateRangeFilter: true,
        companyFilter: true,
        dateFieldNames: {
          startField: 'startDate',
          endField: 'endDate'
        }
      },
      subTabs: ['dados','documentos'],
      columns: [
        // { field: "id", header: "Id", sortable: true, filterable: true, search: true, searchType: "number" },
        // { field: "name", 
        //   header: "Nome", 
        //   sortable: true,
        //   filterable: true, 
        //   search: true, 
        //   searchType: "text" 
        // },
        // { 
        //   field: "description", 
        //   header: "Descrição", 
        //   sortable: true, 
        //   filterable: true, 
        //   search: false, 
        //   searchType: "text" 
        // },
        { 
          field: "contractNumber", 
          header: "Numero", 
          sortable: true, 
          filterable: true, 
          search: true, 
          searchType: "text" 
        },
        {
          field: "startDate",
          header: "Data de Início",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date"
        },
        {
          field: "endDate",
          header: "Data de Término",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date"
        },
        {
          field: "status",
          header: "Status",
          sortable: true,
          filterable: true,
          allowHtml: true,
          search: true,
          searchType: "select",
          searchOptions: [
            { value: 'PENDING', label: 'Pendente' },
            { value: 'ACTIVE', label: 'Ativo' },
            { value: 'INACTIVE', label: 'Inativo' },
            { value: 'EXPIRED', label: 'Expirado' },
            { value: 'CANCELED', label: 'Cancelado' }
          ],
          label: (value: any) => {
            const statusConfig: { [key: string]: { label: string, class: string } } = {
              'active': { label: 'Ativo', class: 'status-active' },
              'inactive': { label: 'Inativo', class: 'status-inactive' },
              'expired': { label: 'Expirado', class: 'status-expired' },
              'canceled': { label: 'Cancelado', class: 'status-canceled' },
              'pending': { label: 'Pendente', class: 'status-pending' },
            };
            const config = statusConfig[value?.toLowerCase()] || { label: value, class: 'status-unknown' };
            return `<span class="status-badge ${config.class}">${config.label}</span>`;
          }
        },
        {
          field: "personName",
          header: "Cliente/Fornecedor",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "text",
        },
        // {
        //   field: "contractProvider",
        //   header: "Prestador ou Contratante",
        //   sortable: true,
        //   filterable: true,
        //   allowHtml: true,
        //   search: true,
        //   searchType: "select",          
        //   searchOptions: [
        //     { value: 'provider', label: 'Prestador' },
        //     { value: 'client', label: 'Contratante' },
        //   ],
        //   label: (value: any) => {
        //     const contractProvider: { [key: string]: { label: string, class: string } } = {
        //       'provider': { label: 'Prestador', class: 'contract-provider' },
        //       'client': { label: 'Contratante', class: 'contract-client' },

        //     };
        //     const config = contractProvider[value?.toLowerCase()] || { label: value, class: 'contractprovider-unknown' };
        //     return `<span class="contractprovider-badge ${config.class}">${config.label}</span>`;
        //   }
        // },
        {
          field: "contractType",
          header: "Modelo de Contrato",
          sortable: true,
          filterable: true,
          allowHtml: true,
          search: true,
          searchType: "select",
          searchOptions: [
            { value: 'rental', label: 'Aluguel' },
            { value: 'clt', label: 'CLT' },
            { value: 'freelancer', label: 'Freelancer' },
            { value: 'fix', label: 'Frota Fixa' },
            { value: 'aggregated', label: 'Agregado' },
            { value: 'outsourced', label: 'Terceirizado' },
            { value: 'custom', label: 'Customizado' },
          ],
          label: (value: any) => {
            const contractType: { [key: string]: { label: string, class: string } } = {
              'rental': { label: 'Aluguel', class: 'modelcontract-rental' },
              'clt': { label: 'CLT', class: 'modelcontract-clt' },
              'freelancer': { label: 'Freelancer', class: 'modelcontract-freelancer' },
              'fix': { label: 'Frota Fixa', class: 'modelcontract-fix' },
              'aggregated': { label: 'Agregado', class: 'modelcontract-aggregated' },
              'outsourced': { label: 'Terceirizado', class: 'modelcontract-outsourced' },
              'custom': { label: 'Customizado', class: 'modelcontract-custom' }
            };
            const config = contractType[value?.toLowerCase()] || { label: value, class: 'modelcontract-unknown' };
            return `<span class="modelcontract-badge ${config.class}">${config.label}</span>`;
          }
        },
        {
          field: "createdAt",
          header: "Criado em",
          sortable: true,
          filterable: true,
          search: false,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
        }
      ],
      sideCard: {
        enabled: false,
        title: "Resumo do Contract",
        position: "right",
        width: "400px",
        component: "summary",
        data: {
          displayFields: [
            {
              key: "name",
              label: "Nome",
              type: "text"
            },
            {
              key: "status",
              label: "Status",
              type: "status"
            },
            {
              key: "created_at",
              label: "Criado em",
              type: "date"
            }
          ],
          statusField: "status"
        }
      }
    };
  }

  getFormConfig(): TabFormConfig {
    return {
      title: 'Dados do Contract',
      entityType: 'contract',
      fields: [],
      submitLabel: 'Salvar Contract',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-info-circle',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['name'],
          fields: [
            {
              key: 'contractNumber',
              label: 'Número',
              type: 'text',
              required: true,
              placeholder: 'Digite o número'
            },
            {
              key: 'companyId',
              label: '',
              labelField: 'companyName',
              type: 'remote-select',
              remoteConfig: {
                service: this.companyService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                placeholder: 'Digite o nome da empresa...',
              }
            },      
            {
              key: 'personId',
              label: '',
              type: 'remote-select',
              required: false,
              labelField: 'personName',
              placeholder: 'Selecione o cliente',
              remoteConfig: {
                service: this.personService,
                searchField: 'name',
                displayField: 'name',
                valueField: 'id',
                placeholder: 'Digite o nome da pessoa...'
              }
            },
            {
              key: 'startDate',
              label: 'Data de Início',
              type: 'date',
              required: true,
              placeholder: 'Digite a data de início'
            },
            {
              key: 'endDate',
              label: 'Data de Término',
              type: 'date',
              required: true,
              placeholder: 'Digite a data de término'
            },
            {
              key: 'status',
              label: 'Status',
              type: 'select',
              required: true,
              options: [
                { value: 'ACTIVE', label: 'Ativo' },
                { value: 'INACTIVE', label: 'Inativo' },
                { value: 'EXPIRED', label: 'Expirado' },
                { value: 'CANCELED', label: 'Cancelado' },
                { value: 'PENDING', label: 'Pendente' }
              ]
            },
            // {
            //   key: 'contractProvider',
            //   label: 'Prestador ou Contratante',
            //   type: 'select',
            //   required: true,
            //   options: [
            //     { value: 'provider', label: 'Prestador' },
            //     { value: 'client', label: 'Contratante' }
            //   ]
            // },
            {
              key: 'contractType',
              label: 'Modelo de Contrato',
              type: 'select',
              required: true,
              options: [
                { value: 'rental', label: 'Aluguel' },
                { value: 'clt', label: 'CLT' },
                { value: 'freelancer', label: 'Freelancer' },
                { value: 'fix', label: 'Frota Fixa' },
                { value: 'aggregated', label: 'Agregado' },
                { value: 'outsourced', label: 'Terceirizado' },
                { value: 'custom', label: 'Customizado' }
              ]
            },
            {
              key: 'description',
              label: 'Descrição',
              type: 'textarea-input',
              required: false,
              placeholder: 'Digite a descrição'
            }                       
          ]
        },
        {
          id: 'documentos',
          label: 'Documentos',
          icon: 'fa-file-pdf',
          enabled: true,
          order: 2,
          templateType: 'fields',
          requiredFields: ['attachment'],
          fields: [
            {
              key: 'attachment',
              label: 'Documentos do Contrato',
              type: 'send-pdf',
              required: false,
              pdfConfiguration: {
                maxDocuments: 8,
                maxSizeMb: 15,
                allowedTypes: ['application/pdf'],
                existingDocuments: [], // Será preenchido dinamicamente
                pendingDocuments: [
                  {
                    name: 'Contrato Assinado',
                    description: 'Documento obrigatório - Contrato principal assinado pelas partes',
                    required: true,
                    status: 'pending'
                  },
                  {
                    name: 'Termos e Condições',
                    description: 'Documento obrigatório - Termos e condições específicos do contrato',
                    required: true,
                    status: 'pending'
                  },
                  {
                    name: 'Anexos Complementares',
                    description: 'Documentos complementares e anexos do contrato',
                    required: false,
                    status: 'pending'
                  }
                ]
              }
            }
          ]
        },
        // {
        //   id: 'photos',
        //   label: 'Fotos',
        //   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: []
        //       }
        //     }
        //   ]
        // }
      ]
    };
  }

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