import { Component, ChangeDetectorRef } from "@angular/core";
import { CommonModule, DatePipe } from "@angular/common";
import { MatDialog } from "@angular/material/dialog";
import { Observable } from "rxjs";

import { TitleService } from "../../shared/services/theme/title.service";
import { HeaderActionsService } from "../../shared/services/header-actions.service";
import { CustomerService } from "./customer.service";
import { Customer } from "./customer.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 "../../shared/services/person.service";
import { CnpjService } from "../../shared/services/cnpj.service";
/**
 * 🎯 CustomerComponent - Gestão de Clientes
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-customer',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './customer.component.html',
  styleUrl: './customer.component.scss'
})
export class CustomerComponent extends BaseDomainComponent<Customer> {

  constructor(
    private customerService: CustomerService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService,
    private personService: PersonService,
    private cnpjService: CnpjService,
    private dialog: MatDialog
  ) {
    super(titleService, headerActionsService, cdr, customerService);
    this.registerFormConfig();
  }

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

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'customer',
      title: 'Clientes',
      entityName: 'cliente',      
      pageSize: 50,
      subTabs: ['dados', 'photos'],
      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: "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) => {
            if (!value) return '<span class="status-badge status-unknown">Não informado</span>';
            
            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: "created_at",
          header: "Criado em",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
        }
      ],
      sideCard: {
        enabled: true,
        title: "Resumo do Customer",
        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 Customer',
      entityType: 'customer',
    
      titleFallback: 'Novo Cliente',
      submitLabel: 'Salvar Veículo',
      fields: [],
      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: '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: []
              }
            }
          ]
        }
      ]
    };
  }

  // ========================================
  // 👥 SOBRESCRITA DO MÉTODO CREATENEW PARA MODAL
  // ========================================
  
  /**
   * 🎯 Sobrescreve o método createNew para abrir modal personalizado
   * Ao invés do formulário padrão, abre modal de cadastro rápido
   */
  override async createNew(): Promise<void> {
    this.openCustomerCreateModal().subscribe((customer: Customer) => {
      if (customer) {
        // Cliente criado com sucesso - apenas recarregar lista
        this.loadEntities();
      }
    });
  }

  protected override getNewEntityData(): Partial<Customer> {
    // Não usado mais - createNew foi sobrescrito
    return {
      name: '',
      status: 'active',
      is_active: true,
      type: 'fisica'
    };
  }

  /**
   * 🚀 Abre modal de criação de cliente com busca automática
   */
  private openCustomerCreateModal(): Observable<Customer> {
    return new Observable<Customer>(observer => {
      import('./components/customer-create-modal/customer-create-modal.component').then(m => {
        const dialogRef = this.dialog.open(m.CustomerCreateModalComponent, {
          width: '600px',
          maxWidth: '90vw',
          maxHeight: '90vh',
          disableClose: false,
          panelClass: 'custom-dialog-container',
          data: {}
        });

        dialogRef.afterClosed().subscribe(result => {
          if (result) {
            console.log('✅ Cliente criado:', result);
            this.loadEntities
            observer.next(result);
            observer.complete();
          } else {
            observer.complete();
          }
        });
      });
    });
  }
}