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 { CompanyService } from "./company.service";
import { Company } from "./company.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";

/**
 * 🎯 CompanyComponent - Gestão de Empresas
 * 
 * Exemplo MÍNIMO de como criar domínios com BaseDomainComponent.
 * 
 * 🚀 Para novos domínios: copie, cole, configure getDomainConfig() e pronto!
 */
@Component({
  selector: 'app-company',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './company.component.html',
  styleUrl: './company.component.scss'
})
export class CompanyComponent extends BaseDomainComponent<Company> {

  constructor(
    private companyService: CompanyService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService
  ) {
    super(titleService, headerActionsService, cdr, companyService);
    
    // 🚀 REGISTRAR configuração específica de empresas
    this.registerCompanyFormConfig();
  }

  /**
   * 🎯 NOVO: Registra a configuração de formulário específica para empresas
   * Chamado no construtor para garantir que está disponível
   */
  private registerCompanyFormConfig(): void {
    this.tabFormConfigService.registerFormConfig('company', () => this.getCompanyFormConfig());
  }

  // ========================================
  // 🎯 ÚNICA CONFIGURAÇÃO NECESSÁRIA
  // ========================================
  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'company',
      title: 'Empresas',
      entityName: 'empresa',
      subTabs: ['dados', 'endereco', 'fiscal', 'documentos'],
      columns: [
        { field: "id", header: "Id", sortable: true, filterable: true },
        { field: "name", header: "Nome", sortable: true, filterable: true },
        { field: "social_reason", header: "Razão Social", sortable: true, filterable: true },
        { field: "cnpj", header: "CNPJ", sortable: true, filterable: true },
        { field: "email", header: "Email", sortable: true, filterable: true },
        { field: "phone", header: "Telefone", sortable: true, filterable: true },
        { field: "address_city", header: "Cidade", sortable: true, filterable: true },
        { field: "address_uf", header: "UF", sortable: true, filterable: true },
        { field: "cnae", header: "CNAE", sortable: true, filterable: true },
        { field: "tax_profile", header: "Perfil Tributário", sortable: true, filterable: true },
        {
          field: "parent_company",
          header: "Empresa Matriz",
          sortable: true,
          filterable: true,
          allowHtml: true,
          label: (value: any) => {
            return value ? '<span class="status-badge status-active">Sim</span>' : '<span class="status-badge status-inactive">Não</span>';
          }
        },
        {
          field: "createdAt",
          header: "Data de Criação",
          sortable: true,
          filterable: true,
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy") || "-"
        }
      ]
    };
  }

  // ========================================
  // 🎯 CONFIGURAÇÃO DO FORMULÁRIO
  // ========================================
  getCompanyFormConfig(): TabFormConfig {
    return {
      title: 'Dados da Empresa',
      entityType: 'company',
      fields: [],
      submitLabel: 'Salvar Empresa',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-building',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['name', 'social_reason', 'cnpj', 'email', 'tax_profile'],
          fields: [
            {
              key: 'name',
              label: 'Nome Fantasia',
              type: 'text',
              required: true,
              placeholder: 'Digite o nome fantasia da empresa'
            },
            {
              key: 'social_reason',
              label: 'Razão Social',
              type: 'text',
              required: true,
              placeholder: 'Digite a razão social da empresa'
            },
            {
              key: 'cnpj',
              label: 'CNPJ',
              type: 'text',
              required: true,
              mask: '00.000.000/0000-00',
              placeholder: '00.000.000/0000-00'
            },
            {
              key: 'email',
              label: 'Email',
              type: 'email',
              required: true,
              placeholder: 'contato@empresa.com.br'
            },
            {
              key: 'phone',
              label: 'Telefone',
              type: 'tel',
              mask: '(00) 00000-0000',
              placeholder: '(11) 99999-9999'
            },
            {
              key: 'parent_company',
              label: 'Tipo de Empresa',
              type: 'select',
              returnObjectSelected: true,
              options: [
                { value: false, label: 'Empresa Filial' },
                { value: true, label: 'Empresa Matriz' }
              ]
            }
          ]
        },
        {
          id: 'endereco',
          label: 'Endereço',
          icon: 'fa-map-marker-alt',
          enabled: true,
          order: 2,
          templateType: 'fields',
          fields: [
            {
              key: 'address_street',
              label: 'Logradouro',
              type: 'text',
              placeholder: 'Rua, Avenida, etc.'
            },
            {
              key: 'address_number',
              label: 'Número',
              type: 'text',
              placeholder: '123'
            },
            {
              key: 'address_complement',
              label: 'Complemento',
              type: 'text',
              placeholder: 'Sala, Andar, etc.'
            },
            {
              key: 'address_neighborhood',
              label: 'Bairro',
              type: 'text',
              placeholder: 'Nome do bairro'
            },
            {
              key: 'address_city',
              label: 'Cidade',
              type: 'text',
              placeholder: 'Nome da cidade'
            },
            {
              key: 'address_uf',
              label: 'UF',
              type: 'text',
              placeholder: 'SP'
            },
            {
              key: 'address_cep',
              label: 'CEP',
              type: 'text',
              mask: '00000-000',
              placeholder: '00000-000'
            }
          ]
        },
        {
          id: 'fiscal',
          label: 'Dados Fiscais',
          icon: 'fa-file-invoice-dollar',
          enabled: true,
          order: 3,
          templateType: 'fields',
          fields: [
            {
              key: 'cnae',
              label: 'CNAE',
              type: 'text',
              placeholder: 'Código CNAE'
            },
            {
              key: 'tax_profile',
              label: 'Perfil Tributário',
              type: 'select',
              required: true,
              options: [
                { value: 'SimplesNacional', label: 'Simples Nacional' },
                { value: 'LucroPresumido', label: 'Lucro Presumido' },
                { value: 'LucroReal', label: 'Lucro Real' },
                { value: 'SociedadeAnonima', label: 'Sociedade Anônima' },
                { value: 'SLU', label: 'SLU' },
                { value: 'MEI', label: 'MEI' },
                { value: 'LLC', label: 'LLC' },
                { value: 'Corporation', label: 'Corporation' },
                { value: 'SoleProprietorship', label: 'Sole Proprietorship' },
                { value: 'Partnership', label: 'Partnership' },
                { value: 'NonProfit', label: 'Non Profit' }
              ]
            },
            {
              key: 'state_registration',
              label: 'Inscrição Estadual',
              type: 'text',
              placeholder: 'Inscrição Estadual'
            },
            {
              key: 'municipal_registration',
              label: 'Inscrição Municipal',
              type: 'text',
              placeholder: 'Inscrição Municipal'
            }
          ]
        }
      ]
    };
  }

  protected override getNewEntityData(): Partial<Company> {
    return {
      name: '',
      social_reason: '',
      cnpj: '',
      municipal_registration: '',
      state_registration: '',
      cnae: '',
      tax_profile: '',
      parent_company: false,
      phone: '',
      email: '',
      address_street: '',
      address_city: '',
      address_cep: '',
      address_uf: '',
      address_number: '',
      address_complement: '',
      address_neighborhood: ''
    };
  }
} 