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

import { TitleService } from "../../shared/services/theme/title.service";
import { HeaderActionsService } from "../../shared/services/header-actions.service";
import { UserService } from "./user.service";
import { User } from "./user.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 { passwordMatchValidator, passwordStrengthValidator } from "../../shared/validators/custom-validators";

/**
 * 🎯 UserComponent - Gestão de Usuários
 * 
 * Campos da API:
 * - id: number
 * - email: string
 * - name: string | null
 * - phone: string | null
 * - photoId: number | null
 * - createdAt: string
 * - updatedAt: string
 * 
 * ✨ Implementa BaseDomainComponent + Registry Pattern
 * 🚀 Auto-registro de configurações para escalabilidade infinita!
 */
@Component({
  selector: 'app-user',
  standalone: true,
  imports: [CommonModule, TabSystemComponent],
  providers: [DatePipe],
  templateUrl: './user.component.html',
  styleUrl: './user.component.scss'
})
export class UserComponent extends BaseDomainComponent<User> {

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

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

  protected override getDomainConfig(): DomainConfig {
    return {
      domain: 'user',
      title: 'Usuários',
      entityName: 'usuário',
      pageSize: 50,
      subTabs: ['dados', 'photos','security'],
      columns: [
        { field: "id", header: "Id", sortable: true, filterable: true, search: true, searchType: "number" },
        { field: "email", header: "E-mail", sortable: true, filterable: true, search: true, searchType: "text" },
        { field: "name", header: "Nome", sortable: true, filterable: true, search: true, searchType: "text" },
        { field: "phone", header: "Telefone", sortable: true, filterable: true, search: true, searchType: "text" },
        { field: "isApi", header: "API", 
          sortable: true, filterable: true, 
          allowHtml: true,
          search: true, 
          searchType: "select", 
          searchOptions: [
            { value: true, label: 'Sim' },
            { value: false, label: 'Não' }
          ],
          label: (value: boolean) => {
            return `<span class="status-badge ${value ? 'status-active' : 'status-inactive'}">${value ? 'Sim' : 'Não'}</span>`;
          }
        },
        { field: "tenantId", header: "Tenant ID", sortable: true, filterable: true, search: true, searchType: "text" },
        {
          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") || "-"
        },
        {
          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") || "-"
        }
      ],
      sideCard: {
        enabled: true,
        title: "Resumo do Usuário",
        position: "right",
        width: "400px",
        component: "summary",
        data: {
          displayFields: [
            {
              key: "name",
              label: "Nome",
              type: "text"
            },
            {
              key: "email",
              label: "E-mail",
              type: "text"
            },
            {
              key: "phone",
              label: "Telefone",
              type: "text"
            },
            {
              key: "isApi",
              label: "API",
              type: "badge",
              format: (value: any) => value ? "Sim" : "Não"
            },
            // {
            //   key: "tenantId",
            //   label: "Tenant ID",
            //   type: "text"
            // },
            {
              key: "createdAt",
              label: "Criado em",
              type: "date",
              format: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
            },
            {
              key: "updatedAt",
              label: "Última atualização",
              type: "date",
              format: (date: any) => this.datePipe.transform(date, "dd/MM/yyyy HH:mm") || "-"
            }
          ]
        }
      }
    };
  }

  getFormConfig(): TabFormConfig {
    return {
      title: 'Dados do Usuário',
      entityType: 'user',
      fields: [],
      submitLabel: 'Salvar Usuário',
      showCancelButton: true,
      subTabs: [
        {
          id: 'dados',
          label: 'Dados Básicos',
          icon: 'fa-info-circle',
          enabled: true,
          order: 1,
          templateType: 'fields',
          requiredFields: ['email', 'password', 'passwordConfirmation'],
          fields: [
            {
              key: 'name',
              label: 'Nome',
              type: 'text',
              required: false,
              placeholder: 'Digite o nome completo'
            },
            {
              key: 'email',
              label: 'E-mail',
              type: 'email',
              required: true,
              placeholder: 'Digite o e-mail'
            },           
            {
              key: 'phone',
              label: 'Telefone',
              type: 'text',
              required: false,
              placeholder: '(00) 00000-0000',
              mask: '(00) 00000-0000'
            },
            {
              key: 'isApi',
              label: 'API',
              type: 'select',
              required: false,
              options: [
                { value: true, label: 'Sim' },
                { value: false, label: 'Não' }
              ]
            }
          ]
        },
        {
          id: 'photos',
          label: 'Fotos', 
          icon: 'fa-camera',
          enabled: true,
          order: 2,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            {
              key: 'photoId',
              label: 'Fotos',
              type: 'send-image',
              required: false,
              imageConfiguration: {
                maxImages: 1,
                maxSizeMb: 5,
                allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
                existingImages: []
              }
            }
          ]
        },
        {
          id: 'security',
          label: 'Segurança',
          icon: 'fa-shield-alt',
          enabled: true,
          order: 3,
          templateType: 'fields',
          requiredFields: [],
          fields: [
            // {
            //   key: 'tenantId',
            //   label: 'Tenant ID',
            //   type: 'text',
            //   required: false,
            //   readOnly: true,
            //   placeholder: 'Carregado automaticamente',
            //   helpText: 'Identificador único da organização (obtido automaticamente)'
            // },
            {
               key: 'password',
               label: 'Senha',
               type: 'password-input',
               required: true,
               placeholder: 'Digite a senha',
               showStrengthIndicator: true,
               allowToggleVisibility: true,
               helpText: 'Sua senha deve ser forte e segura',
               validators: [
                 Validators.minLength(8),
                 passwordStrengthValidator()
               ]
             },
             {
               key: 'passwordConfirmation',
               label: 'Confirmação de Senha',
               type: 'password-input',
               required: true,
               placeholder: 'Digite a senha novamente',
               allowToggleVisibility: true,
               helpText: 'Repita a senha digitada acima',
               validators: [
                 passwordMatchValidator('password')
               ]
             }
          ]
        }
      ]
    };
  }

  protected override getNewEntityData(): Partial<User> {
    // 🔐 Obter tenantId automaticamente do localStorage
    const tenantId = localStorage.getItem('tenant_id');
    
    return {
      email: '',
      name: '',
      phone: '',
      password: '',
      passwordConfirmation: '',
      photoId: null,
      isApi: false,
      tenantId: tenantId
    };
  }
}