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 { ProductService } from "./product.service";
import { Product } from "./product.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";

/**
 * 🎯 ProductComponent - Gestão de Produtos
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-product',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './product.component.html',
  styleUrl: './product.component.scss'
})
export class ProductComponent extends BaseDomainComponent<Product> {

  constructor(
    private productService: ProductService,
    titleService: TitleService,
    headerActionsService: HeaderActionsService,
    cdr: ChangeDetectorRef,
    private datePipe: DatePipe,
    private tabFormConfigService: TabFormConfigService
  ) {
    super(titleService, headerActionsService, cdr, productService);
    this.registerFormConfig();
  }

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

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'product',
      title: 'Produtos',
      entityName: 'Produto',
      pageSize: 50,
      subTabs: ['dados'],
      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" },
        
        /**
            * ✨ Exibição do status na lista d eprodutos.
        */

        // {
        //   field: "status",
        //   header: "Status",
        //   sortable: true,
        //   filterable: true,
        //   allowHtml: true,
        //   search: true,
        //   searchType: "select",
        //   searchOptions: [
        //     { value: 'available', label: 'Disponível' },
        //     { value: 'sold', label: 'Vendido' },
        //   ],
        //   label: (value: any) => {
        //     if (!value) return '<span class="status-badge status-unknown">Não informado</span>';
            
        //     const statusConfig: { [key: string]: { label: string, class: string } } = {
        //       'available': { label: 'Disponível', class: 'status-available' },
        //       'sold': { label: 'Vendido', class: 'status-sold' },                         
        //     };    
            
        //     const config = statusConfig[value.toLowerCase()] || { label: value, class: 'status-unknown' };
        //     return `<span class="status-badge ${config.class}">${config.label}</span>`;
        //   }
        // },
        {
          field: "unitMeasurement",
          header: "Unidade de Medida",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "text",
        },
        {
          field: "code",
          header: "Código",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "text",
        },
        {
          field: 'updatedAt',
          header: "Atualizado em",
          sortable: true,
          filterable: true,
          search: true,
          searchType: "date",
          label: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
        },  
        {
          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 Product',
      entityType: 'product',
      fields: [],
      submitLabel: 'Salvar Produto',
      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: 'code',
              label: 'Código',
              type: 'text',
              required: true,
              placeholder: 'Digite o Código'
            },
            {
              key: 'unitMeasurement',
              label: 'Unidade de Medida',
              type: 'select',
              required: true,
              options: [
                { value: 'MT', label: 'Metros' },
                { value: 'KG', label: 'Quilograma' },
                { value: 'LT', label: 'Litros' },
                { value: 'UN', label: 'Unidades' },
                { value: 'BX', label: 'Brix' },
                { value: 'PK', label: 'Pacote' },
              ]
            },
          ]
        },
        {
          id: 'stock',
          label: 'Estoque',
          icon: 'fas fa-boxes-stacked',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['name'],
          fields: [
            {
              key: 'quantity',
              label: 'quantidade',
              type: 'number',
              required: false,
              placeholder: 'Informe a quantidade'
            },
            {
              key: 'category',
              label: 'Categoria',
              type: 'text',
              required: false,
              placeholder: 'Informe a Categoria'
            },
            {
              key: 'status',
              label: 'Status',
              type: 'select',
              required: false,
              options: [
                { value: 'available', label: 'Disponível' },
                { value: 'unavailable', label: 'Indisponível' },
                { value: 'soldOut', label: 'Esgotado' },
              ]
            },
          ]
        }
      ],

      sideCard: {
        enabled: true,
        title: "Resumo do Produto",
        position: "right",
        width: "400px",
        component: "summary",
        data: {
          // imageField: "photoIds", // use se existir imagem
          displayFields: [
            {
              key: "name",
              label: "Nome",
              type: "text"
            },
            {
              key: "code",
              label: "Código",
              type: "text"
            },
            // {
            //   key: "quantity",
            //   label: "Quantidade",
            //   type: "number"
            // },
            // {
            //   key: "category",
            //   label: "Categoria",
            //   type: "text"
            // },
            // {
            //   key: "status",
            //   label: "Status",
            //   type: "status"
            // },
            {
              key: "updatedAt",
              label: "Atualizado em",
              type: "date",
              format: (value: any) => this.datePipe.transform(value, "dd/MM/yyyy HH:mm") || "-"
            },
            {
              key: "createdAt",
              label: "Criado em",
              type: "date",
              format: (value: any) => this.datePipe.transform(value, "dd/MM/yyyy HH:mm") || "-"
            }
          ],

          statusField: "status",
          statusConfig: {
            "available": {
              label: "Disponível",
              color: "#d4edda",
              textColor: "#155724",
              icon: "fa-check-circle"
            },
            "sold": {
              label: "Vendido",
              color: "#f8d7da",
              textColor: "#721c24",
              icon: "fa-dollar-sign"
            },
            "": {
              label: "Não informado",
              color: "#fff3cd",
              textColor: "#856404",
              icon: "fa-exclamation-triangle"
            },
            "*": {
              label: "Status não definido",
              color: "#f5f5f5",
              textColor: "#666",
              icon: "fa-question-circle"
            }
          }
        }
      }
    };
  }

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