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

import { TitleService } from "../../../../shared/services/theme/title.service";
import { HeaderActionsService } from "../../../../shared/services/header-actions.service";
import { AccountPayableService } from "../services/accountpayable.service";
import { AccountPayable, CategoryType, CATEGORY_CONFIGS } from "../interfaces/accountpayable.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 { AccountPayableItemsComponent } from "./account-payable-items/account-payable-items.component";
import { CsvImporterDialogService } from "../../../../shared/components/csv-importer/csv-importer-dialog.service";
import { SnackNotifyService } from "../../../../shared/components/snack-notify/snack-notify.service";
import { Attachments } from "../../../../shared/interfaces/attachments";
import { map, Observable } from "rxjs";

/**
 * 🏦 AccountPayableComponent - Sistema de Contas a Pagar
 * 
 * Migrado para seguir o padrão BaseDomainComponent com:
 * ✅ Tab System integrado
 * ✅ CRUD automático
 * ✅ Registry Pattern para formulários
 * ✅ Status badges funcionais
 * ✅ Categorias com ícones visuais
 */
@Component({
  selector: "app-finance-accountpayable",
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe, CurrencyPipe],
  templateUrl: './account-payable.component.html',
  styleUrl: './account-payable.component.scss'
})
export class AccountPayableComponent extends BaseDomainComponent<AccountPayable> {

  // 🎯 Propriedade para rastrear ID da entidade selecionada (para sub-componentes)
  currentSelectedEntityId: number | string | null = null;

  constructor(
    private serviceAccountPayable: AccountPayableService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private currencyPipe: CurrencyPipe,
    private tabFormConfigService: TabFormConfigService,
    private csvImporterDialog: CsvImporterDialogService,
    private snackNotify: SnackNotifyService
  ) {  
    super(titleService, headerActionsService, cdr, serviceAccountPayable); 
    this.registerFormConfig();
  }

  private registerFormConfig(): void {
    this.tabFormConfigService.registerFormConfig('account-payable', () => this.getFormConfig());
  }
  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'account-payable',
      title: 'Contas a Pagar',
      entityName: 'conta a pagar',
      subTabs: ['dados', 'itens', 'photos'],
      pageSize: 200,
      columns: [
        { field: "id", header: "ID", sortable: true, filterable: true },
        { 
          field: "status", 
          header: "Status", 
          sortable: true, 
          filterable: true,
          search: true,
          searchType: "select",
          allowHtml: true,
          searchOptions: [
            { value: 'pending', label: 'Pendente' },
            { value: 'paid', label: 'Pago' },
            { value: 'approved', label: 'Aprovado para pagamento' },
            { value: 'approvedcustomer', label: 'Aprovado pelo Cliente' },
            { value: 'refused', label: 'Recusado' },
            { value: 'cancelled', label: 'Cancelado' },
            { value: 'advancerequested', label: 'Solicitado antecipação' },
            { value: 'requestAdvanceApproved', label: 'Aprovado antecipação' },
            { value: 'requestAdvanceRefused', label: 'Recusado antecipação' },
          ],
          label: (status: string) => {
            const statusConfig: { [key: string]: { label: string, class: string } } = {
              'pending': { label: 'Pendente', class: 'status-pending' },
              'paid': { label: 'Pago', class: 'status-paid' },
              'approved': { label: 'Aprovado para pagamento', class: 'status-approved' },
              'approvedcustomer': { label: 'Aprovado pelo Cliente', class: 'status-approved-customer' },
              'refused': { label: 'Recusado', class: 'status-refused' },
              'cancelled': { label: 'Cancelado', class: 'status-cancelled' } ,
              'advancerequested': { label: 'Solicitada antecipação', class: 'status-requested-advance' },
              'requestAdvanceApproved': { label: 'Aprovado antecipação', class: 'status-requested-advance-approved' },
              'requestAdvanceRefused': { label: 'Recusado antecipação', class: 'status-requested-advance-refused' },
            };
            
            const config = statusConfig[status?.toLowerCase()] || { label: status, class: 'status-unknown' };
            return `<span class="status-badge ${config.class}">${config.label}</span>`;
          }
        
        },
        { field: "number_document", 
          header: "Nº Documento", 
          sortable: true,
          filterable: true 
        },
        { field: "documentDate", 
          header: "Data do Documento", 
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy") || "-"
        },

        { field: "person_name", header: "Fornecedor", sortable: true, filterable: true },
        {
          field: "expiration_date",
          header: "Vencimento",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date",
          date: true // ✅ PADRÃO RECOMENDADO: Usar date: true
          // ❌ REMOVIDO: label customizado não é mais necessário
        },
        {
          field: "total",
          header: "Valor",
          sortable: true,
          filterable: true,
          label: (total: any) => {
            if (!total) return '-';
            return `R$ ${Number(total).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}`;
          }
        },
        { 
          field: "category_name", 
          header: "Categoria", 
          sortable: true, 
          filterable: true,
          allowHtml: true,
          label: (category: CategoryType | string) => this.getCategoryBadge(category)
        },
        // { field: "installments", header: "Parcelas", sortable: true, filterable: true },
        // {
        //   field: "attachmentsIds",
        //   header: "Anexos",
        //   sortable: false,
        //   filterable: false,
        //   allowHtml: true,
        //   label: (attachments: string[] | any) => this.getPhotosDisplay(attachments)
        // }
      ]
    };
  }
  private getCategoryBadge(categoryKey: CategoryType | string): string {
    const categoryConfig = CATEGORY_CONFIGS.find(config => config.key === categoryKey);
    
    if (!categoryConfig) {   
      const uncategorized = CATEGORY_CONFIGS.find(config => config.key === 'uncategorized')!;
      return `
        <span class="category-badge" style="background-color: ${uncategorized.bgColor}; color: ${uncategorized.color};">
          <i class="fas ${uncategorized.icon}"></i>
          ${uncategorized.label}
        </span>
      `;
    }

    return `
      <span class="category-badge" style="background-color: ${categoryConfig.bgColor}; color: ${categoryConfig.color};">
        <i class="fas ${categoryConfig.icon}"></i>
        ${categoryConfig.label}
      </span>
    `;
  }

  private getPhotosDisplay(attachments: string[] | any): string {
    // Verificar se attachments é um array válido
    if (!Array.isArray(attachments) || attachments.length === 0) {
      return `
        <span class="photos-badge no-photos">
          <i class="fas fa-camera text-muted"></i>
          <span class="count">0</span>
        </span>
      `;
    }

    const count = attachments.length;
    const iconColor = count > 0 ? 'text-primary' : 'text-muted';
    const badgeClass = count > 0 ? 'has-photos' : 'no-photos';

    return `
      <span class="photos-badge ${badgeClass}">
        <i class="fas fa-camera ${iconColor}"></i>
        <span class="count">${count}</span>
      </span>
    `;
  }
  getFormConfig(): TabFormConfig {
    return {
      title: 'Conta: {{number_document}} - {{person_name}}',
      titleFallback: 'Nova Conta a Pagar',
      entityType: 'account-payable',
      fields: [],
      submitLabel: 'Salvar Conta',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-file-invoice-dollar',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['person_name', 'number_document', 'total'],
          fields: [
            {
              key: 'person_name',
              label: 'Fornecedor',
              type: 'text',
              required: true,
              placeholder: 'Nome do fornecedor'
            },
            {
              key: 'number_document',
              label: 'Número do Documento',
              type: 'text',
              required: true,
              placeholder: 'Ex: INV-1001, NF-12345'
            },
            {
              key: 'installments',
              label: 'Número de Parcelas',
              type: 'number',
              required: false,
              min: 1,
              max: 60,
              defaultValue: 1
            },
            {
              key: 'documentDate',
              label: 'Data do Documento',
              type: 'date',
              required: true
            },
            {
              key: 'status',
              label: 'Status',
              type: 'select',
              required: true,              
              options: [              
                { value: 'Pending', label: 'Pendente' },
                { value: 'Paid', label: 'Pago' },
                { value: 'Approved', label: 'Aprovado para pagamento' },
                { value: 'ApprovedCustomer', label: 'Aprovado pelo Cliente' },
                { value: 'Refused', label: 'Recusado' },
                { value: 'Cancelled', label: 'Cancelado' },
                { value: 'AdvanceRequested', label: 'Solicitado antecipação' },
                { value: 'AdvanceApprovedRequest', label: 'Aprovado antecipação' },
                { value: 'AdvanceRefusedRequest', label: 'Recusado antecipação' },
              ],
              defaultValue: 'Pending'
            },
            {
              key: 'total',
              label: 'Valor',
              type: 'currency-input',
              required: true,
              placeholder: '0,00',
              min: 0
            },
            {
              key: 'discount',
              label: 'Desconto',
              type: 'number',
              required: false,
              placeholder: '0,00',
              min: 0
            },
            
            {
              key: 'expiration_date',
              label: 'Data de Vencimento',
              type: 'date',
              required: true
            },
            {
              key: 'expected_payment',
              label: 'Data de Pagamento Esperada',
              type: 'date',
              required: true
            },
            {
              key: 'category_name',
              label: 'Categoria',
              type: 'select',
              required: false,
              defaultValue: 'uncategorized',
              options: CATEGORY_CONFIGS.map(config => ({
                value: config.key,
                label: config.label,
                description: config.description,
                icon: config.icon,
                color: config.bgColor
              }))
            },
            {
              key: 'notes',
              label: 'Notas',
              type: 'textarea-input',
              required: false,
              placeholder: 'Notas'
            }
          ]
        },
        {
          id: 'itens',
          label: 'Itens',
          icon: 'fa-list-ul',
          enabled: true,
          order: 2,
          templateType: 'component',
          dynamicComponent: {
            selector: 'app-account-payable-items',
            inputs: {
              accountPayableId: ''
            },
            dataBinding: {
              getInitialData: () => this.getFromDataTab()
           }
          },
          requiredFields: []
        },
        {
          id: 'importar',
          label: 'Importar CSV',
          icon: 'fa-file-csv',
          enabled: true,
          order: 3,
          templateType: 'component',
          dynamicComponent: {
            selector: 'app-csv-importer',
            inputs: {
              maxSizeMb: 10,
              allowMultiple: false,
              showPreview: true,
              autoUpload: false,
              acceptMessage: 'Selecione um arquivo CSV para importar contas a pagar'
            }
          },
          requiredFields: []
        },        
        {
          id: 'photos',
          label: 'Fotos do Documento',
          icon: 'fa-camera',
          enabled: true,
          order: 5,
          templateType: 'fields', // 🎯 Renderiza campos específicos
          // 🎯 NOVA ABORDAGEM: Data Binding dinâmico
          dataBinding: {
            getInitialData: () => this.getAttachmentsIds()
          },
          fields: [
            {
              key: 'attachmentsIds',
              label: 'Fotos do Documento',
              type: 'send-image',
              required: false,
              imageConfiguration: {
                maxImages: 10,
                maxSizeMb: 5,
                allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
                existingImages: [] // Será preenchido dinamicamente via dataBinding
              }
            }
          ]
        },
        // 🎯 EXEMPLO: Abordagem atual (compatibilidade)
        // {
        //   id: 'photos-legacy',
        //   label: 'Fotos (Legacy)',
        //   icon: 'fa-camera',
        //   enabled: false, // Desabilitado para exemplo
        //   order: 6,
        //   templateType: 'fields',
        //   requiredFields: ['attachmentsIds'], // Referencia campo do formulário
        //   fields: [
        //     {
        //       key: 'attachmentsIds',
        //       label: 'Fotos do Documento',
        //       type: 'send-image',
        //       required: false,
        //       imageConfiguration: {
        //         maxImages: 10,
        //         maxSizeMb: 5,
        //         allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
        //         existingImages: [] // Preenchido automaticamente do initialData
        //       }
        //     }
        //   ]
        // },
      ]
    };
  }
  getFromDataTab(): AccountPayable {
        return this.tabSystem?.getSelectedTab()?.data as AccountPayable;  
  }
 
  protected override configureHeaderActions(): void {
    this.headerActionsService.setDomainConfig({
      domain: this.domainConfig.domain,
      title: this.domainConfig.title,
      recordCount: this.totalItems,
      actions: [
        {
          id: `new-${this.domainConfig.domain}`,
          label: `Novo ${this.domainConfig.entityName}`,
          icon: 'add',
          type: 'primary',
          action: () => this.createNew(),
          visible: true,
          tooltip: `Criar novo ${this.domainConfig.entityName}`
        },
        {
          id: `import-${this.domainConfig.domain}`,
          label: 'Importar',
          icon: 'upload',
          type: 'secondary',
          action: () => this.openCsvImporter(),
          visible: true,
          tooltip: 'Importar contas a pagar via CSV'
        }
      ]
    });
  }
  private openCsvImporter(): void {
    console.log('📊 Abrindo CSV Importer para Account Payable...');
    
    this.csvImporterDialog.openAccountPayableCsvImporter()
      .subscribe(result => {
        console.log('🔄 Resultado da importação:', result);
        
        if (result?.success) {
          const imported = result.result?.data?.imported || 0;
          const failed = result.result?.data?.failed || 0;
          
          // Mostrar notificação de sucesso
          this.snackNotify.success(
            `✅ Importação concluída! ${imported} registros importados${failed > 0 ? `, ${failed} falharam` : ''}.`
          );
          
          // Atualizar lista de contas a pagar
          this.loadEntities();
          
          console.log(`✅ ${imported} contas a pagar importadas com sucesso!`);
        } else if (result?.action === 'cancelled') {
          console.log('🚫 Importação cancelada pelo usuário');
        }
      });
  }

  getAttachmentsIds(): Observable<number[]> {
    const currentTab = this.tabSystem?.getSelectedTab();
    return this.serviceAccountPayable.getAttachmentsById(currentTab?.data?.id).pipe(
      map((response: { data: Attachments[] }) => response.data.map((attachment: Attachments) => attachment.id))
    );
  }

   // protected updateSelectedEntity(entity: AccountPayable): void {
  //   this.currentSelectedEntityId = entity?.id || null;
  // }
  // protected onEntityEdit(entity: AccountPayable): void {
  //   this.currentSelectedEntityId = entity?.id || null;
  // }

}
