import { Component, Input, Output, EventEmitter, OnInit, OnChanges, OnDestroy, AfterViewInit, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';

// ✅ Componentes customizados (substituindo Material Design)
import { MultiSelectComponent } from '../multi-select/multi-select.component';
import { CustomInputComponent } from '../inputs/custom-input/custom-input.component';
import { DateRangeFilterComponent, DateRange } from '../filters/date-range-filter/date-range-filter.component';
import { RemoteSelectComponent } from '../remote-select/remote-select.component';
import { DateRangeUtils } from '../../utils/date-range.utils';

import { DomainConfig, DefaultFilter } from '../../components/base-domain/base-domain.component';
import { Column } from '../../components/data-table/data-table.component';
import { 
  SpecialFilter, 
  RawFilters, 
  ProcessedFilters, 
  ProcessedFilter,
  ApiFilters,
  Option 
} from '../../interfaces/domain-filter.interface';
import { CompanyService } from '../../../domain/company/company.service';
import { Company } from '../../../domain/company/company.interface';

@Component({
  selector: 'app-domain-filter',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MultiSelectComponent,
    CustomInputComponent,
    DateRangeFilterComponent,
    RemoteSelectComponent
  ],
  templateUrl: './domain-filter.component.html',
  styleUrl: './domain-filter.component.scss'
})
export class DomainFilterComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
  @Input() domainConfig!: DomainConfig;
  @Input() visible: boolean = false;
  @Input() activeFilters: ApiFilters = {}; // ✅ NOVO: Receber filtros ativos
  @Output() filtersChanged = new EventEmitter<ApiFilters>();
  @Output() visibilityChanged = new EventEmitter<boolean>();

  filters: RawFilters = {};
  searchableFields: Column[] = [];
  specialFilters: SpecialFilter[] = [];
  companyOptions: Option[] = [];
  showCompanyFilter: boolean = true;
  showDateRangeFilter: boolean = false;
  dateRange: DateRange = {};
  
  // ✨ NOVOS: Propriedades para filtros de data de vencimento
  showDueDateOneFilter: boolean = false;
  dueDateOneRange: DateRange = {};
  
  showDueDateTwoFilter: boolean = false;
  dueDateTwoRange: DateRange = {};
  
  private hasInitialized = false;
  private hasAppliedDefaultFilters = false; // ✅ NOVO: Flag para evitar loop

  // ✨ NOVOS: Getters para labels dinâmicos
  get dueDateOneLabel(): string {
    return this.domainConfig.filterConfig?.dueDateOneFieldNames?.label || 'Data de Vencimento 1';
  }

  get dueDateTwoLabel(): string {
    return this.domainConfig.filterConfig?.dueDateTwoFieldNames?.label || 'Data de Vencimento 2';
  }

  constructor(private companyService: CompanyService) {}

  ngOnInit() {
    this.initializeComponent();
  }

  ngAfterViewInit() {
    console.log('🔍 [DEBUG] ngAfterViewInit - View initialized, defaultFilters ready but not applied automatically');
    // ✅ ESTRATÉGIA: Não aplicar automaticamente para evitar loops
    // Os defaultFilters serão aplicados quando o usuário abrir o painel de filtros
    // ou quando explicitamente chamado
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['domainConfig'] && this.hasInitialized) {
      console.log('🔍 [DEBUG] ngOnChanges - domainConfig changed, updating filter configuration');
      this.updateFilterConfiguration();
      // ✅ NÃO re-aplicar defaultFilters aqui para evitar loop
    }
    
    // ✅ NOVO: Sincronizar filtros ativos quando recebidos
    if (changes['activeFilters'] && this.hasInitialized) {
      console.log('🔍 [DEBUG] ngOnChanges - activeFilters changed, syncing');
      this.syncActiveFilters();
    }
    
    // ✅ NOVO: Controlar scroll do body quando modal abrir/fechar
    if (changes['visible']) {
      if (this.visible) {
        // ✅ Bloquear scroll da página
        document.body.classList.add('modal-open');
        // ✅ NOVO: Limpar filtros quando modal abre (sempre começar limpo)
        this.clearFiltersOnOpen();
        
        // ✅ ESTRATÉGIA: defaultFilters são aplicados pelo BaseDomainComponent
        // Não aplicar automaticamente aqui para evitar conflitos e loops
        console.log('🔍 [DEBUG] Modal opened - defaultFilters são gerenciados pelo BaseDomainComponent');
      } else {
        // ✅ Restaurar scroll da página
        document.body.classList.remove('modal-open');
      }
    }
  }

  ngOnDestroy() {
    // ✅ NOVO: Limpar classe ao destruir componente
    document.body.classList.remove('modal-open');
  }

  private initializeComponent() {
    this.updateFilterConfiguration();
    this.applyDefaultFilters();
    this.loadCompanyOptions();
    this.syncActiveFilters(); // ✅ NOVO: Sincronizar filtros na inicialização
    this.hasInitialized = true;
    
    console.log('🔍 [DEBUG] initializeComponent - Completed initialization');
  }
  
  private updateFilterConfiguration() {
    this.searchableFields = this.domainConfig.columns
      ?.filter(col => (col as any).search === true) || [];
    
    // ✅ DEBUG: Log para verificar campos de busca
    console.log('🔍 [DOMAIN-FILTER] Campos de busca encontrados:', {
      totalColumns: this.domainConfig.columns?.length,
      searchableFields: this.searchableFields.map(f => ({
        field: f.field,
        header: f.header,
        searchType: (f as any).searchType,
        hasRemoteConfig: !!(f as any).remoteConfig,
        remoteLabel: (f as any).remoteConfig?.label
      }))
    });
    
    this.specialFilters = this.domainConfig.filterConfig?.specialFilters || [];
    
    this.showCompanyFilter = this.domainConfig.filterConfig?.companyFilter !== false;
    
    // ✅ NOVO: Detectar se deve mostrar filtro de período (date_start/date_end)
    this.showDateRangeFilter = (this.domainConfig.filterConfig as any)?.dateRangeFilter !== false;
    
    // ✨ NOVOS: Detectar filtros de data de vencimento
    this.showDueDateOneFilter = this.domainConfig.filterConfig?.dueDateOneFilter === true;
    this.showDueDateTwoFilter = this.domainConfig.filterConfig?.dueDateTwoFilter === true;
  }

  private applyDefaultFilters() {
    const defaultFilters = this.domainConfig.filterConfig?.defaultFilters || [];
    console.log('🔍 [DEBUG] applyDefaultFilters:', {
      defaultFilters,
      filtersBeforeApply: { ...this.filters }
    });
    
    defaultFilters.forEach((filter: DefaultFilter) => {
      this.filters[filter.field] = filter.value;
      console.log(`✅ [DEBUG] Applied defaultFilter: ${filter.field} = ${filter.value} (operator: ${filter.operator})`);
    });
    
    console.log('🔍 [DEBUG] Filters after apply:', { ...this.filters });
  }

  private loadCompanyOptions() {
    
    this.companyService.getCompanies(1, 10000).subscribe({
      next: (response) => {
        this.companyOptions = response.data.map((company: Company) => ({
          value: company.id,
          label: company.name,
        }));
        
        // ✅ NOVO: Definir todas as empresas como padrão selecionado
        this.setAllCompaniesAsDefault();
      },
      error: (error) => {
        console.warn('⚠️ Erro ao carregar empresas, usando dados de fallback', error);
        // ✅ NOVO: Mesmo em caso de erro, definir padrão vazio
        this.setAllCompaniesAsDefault();
      }
    });
  }

  /**
   * ✨ NOVO: Define todas as empresas como selecionadas por padrão
   */
  private setAllCompaniesAsDefault() {
    // ✅ Selecionar todas as empresas por padrão
    const allCompanyIds = this.companyOptions.map(option => option.value);
    this.filters['companyIds'] = allCompanyIds;
    
    console.log('🏢 Todas as empresas selecionadas por padrão:', {
      totalEmpresas: allCompanyIds.length,
      empresasSelecionadas: allCompanyIds
    });
  }

  /**
   * ✨ NOVO: Limpa todos os filtros quando o modal abre (sempre começar limpo)
   */
  private clearFiltersOnOpen() {
    // ✅ Limpar completamente todos os filtros internos
    this.filters = {};
    this.dateRange = {};
    this.dueDateOneRange = {}; // ✨ NOVO
    this.dueDateTwoRange = {}; // ✨ NOVO
    
    // ✅ Limpar explicitamente campos específicos
    this.searchableFields.forEach(field => {
      this.filters[field.field] = '';
    });
    
    // ✅ NOVO: Manter todas as empresas selecionadas por padrão (não limpar)
    this.setAllCompaniesAsDefault();
    
    // ✅ Limpar filtros de data (com nomes customizáveis)
    const startFieldName = this.domainConfig.filterConfig?.dateFieldNames?.startField || 'date_start';
    const endFieldName = this.domainConfig.filterConfig?.dateFieldNames?.endField || 'date_end';
    this.filters[startFieldName] = '';
    this.filters[endFieldName] = '';
    
    // ✨ NOVOS: Limpar filtros de data de vencimento
    if (this.showDueDateOneFilter) {
      const dueDateOneStart = this.domainConfig.filterConfig?.dueDateOneFieldNames?.startField || 'due_date_one_start';
      const dueDateOneEnd = this.domainConfig.filterConfig?.dueDateOneFieldNames?.endField || 'due_date_one_end';
      this.filters[dueDateOneStart] = '';
      this.filters[dueDateOneEnd] = '';
    }
    
    if (this.showDueDateTwoFilter) {
      const dueDateTwoStart = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.startField || 'due_date_two_start';
      const dueDateTwoEnd = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.endField || 'due_date_two_end';
      this.filters[dueDateTwoStart] = '';
      this.filters[dueDateTwoEnd] = '';
    }
    
    console.log('🧹 Filtros limpos ao abrir modal (empresas mantidas):', {
      filters: this.filters,
      dateRange: this.dateRange,
      dueDateOneRange: this.dueDateOneRange,
      dueDateTwoRange: this.dueDateTwoRange
    });
  }

  /**
   * ✨ NOVO: Sincroniza filtros ativos com os campos do modal
   */
  private syncActiveFilters() {
    if (!this.activeFilters || Object.keys(this.activeFilters).length === 0) {
      return;
    }

    // ✅ Sincronizar campos de busca
    this.searchableFields.forEach(field => {
      const apiFieldName = (field as any).searchField || field.field;
      if (this.activeFilters[apiFieldName]) {
        this.filters[field.field] = this.activeFilters[apiFieldName];
      }
    });

    // ✅ Sincronizar filtro de empresa
    if (this.activeFilters['companyIds']) {
      this.filters['companyIds'] = this.activeFilters['companyIds'];
    }

    // ✅ Sincronizar filtros de data (com nomes customizáveis)
    const startFieldName = this.domainConfig.filterConfig?.dateFieldNames?.startField || 'date_start';
    const endFieldName = this.domainConfig.filterConfig?.dateFieldNames?.endField || 'date_end';
    
    if (this.activeFilters[startFieldName] || this.activeFilters[endFieldName]) {
      this.filters[startFieldName] = this.activeFilters[startFieldName] || '';
      this.filters[endFieldName] = this.activeFilters[endFieldName] || '';
      
      // ✅ Atualizar dateRange para o componente de data
      this.dateRange = {
        start: this.activeFilters[startFieldName] || undefined,
        end: this.activeFilters[endFieldName] || undefined
      };
    }

    // ✨ NOVOS: Sincronizar filtros de data de vencimento
    if (this.showDueDateOneFilter) {
      const dueDateOneStart = this.domainConfig.filterConfig?.dueDateOneFieldNames?.startField || 'due_date_one_start';
      const dueDateOneEnd = this.domainConfig.filterConfig?.dueDateOneFieldNames?.endField || 'due_date_one_end';
      
      if (this.activeFilters[dueDateOneStart] || this.activeFilters[dueDateOneEnd]) {
        this.filters[dueDateOneStart] = this.activeFilters[dueDateOneStart] || '';
        this.filters[dueDateOneEnd] = this.activeFilters[dueDateOneEnd] || '';
        
        this.dueDateOneRange = {
          start: this.activeFilters[dueDateOneStart] || undefined,
          end: this.activeFilters[dueDateOneEnd] || undefined
        };
      }
    }

    if (this.showDueDateTwoFilter) {
      const dueDateTwoStart = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.startField || 'due_date_two_start';
      const dueDateTwoEnd = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.endField || 'due_date_two_end';
      
      if (this.activeFilters[dueDateTwoStart] || this.activeFilters[dueDateTwoEnd]) {
        this.filters[dueDateTwoStart] = this.activeFilters[dueDateTwoStart] || '';
        this.filters[dueDateTwoEnd] = this.activeFilters[dueDateTwoEnd] || '';
        
        this.dueDateTwoRange = {
          start: this.activeFilters[dueDateTwoStart] || undefined,
          end: this.activeFilters[dueDateTwoEnd] || undefined
        };
      }
    }

    console.log('🔄 Filtros sincronizados:', {
      activeFilters: this.activeFilters,
      internalFilters: this.filters,
      dateRange: this.dateRange,
      dueDateOneRange: this.dueDateOneRange,
      dueDateTwoRange: this.dueDateTwoRange
    });
  }

  onFilterChange() {
    // Não emitir automaticamente - apenas preparar filtros
    // A emissão será feita apenas no método applyFilters()
  }

  /**
   * 🗓️ Gerenciar mudanças no range de datas
   */
  onDateRangeChange(dateRange: DateRange) {
    this.dateRange = dateRange;
    // ✅ NOVO: Usar nomes de campos customizados
    const startFieldName = this.domainConfig.filterConfig?.dateFieldNames?.startField || 'date_start';
    const endFieldName = this.domainConfig.filterConfig?.dateFieldNames?.endField || 'date_end';
    
    // Atualizar filtros internos com formato ISO 8601
    this.filters[startFieldName] = DateRangeUtils.formatDateToISO(dateRange.start, 'start');
    this.filters[endFieldName] = DateRangeUtils.formatDateToISO(dateRange.end, 'end');
  }

  /**
   * ✨ NOVO: Gerenciar mudanças no range de data de vencimento 1
   */
  onDueDateOneChange(dateRange: DateRange) {
    this.dueDateOneRange = dateRange;
    const startFieldName = this.domainConfig.filterConfig?.dueDateOneFieldNames?.startField || 'due_date_one_start';
    const endFieldName = this.domainConfig.filterConfig?.dueDateOneFieldNames?.endField || 'due_date_one_end';
    
    // Atualizar filtros internos com formato ISO 8601
    this.filters[startFieldName] = DateRangeUtils.formatDateToISO(dateRange.start, 'start');
    this.filters[endFieldName] = DateRangeUtils.formatDateToISO(dateRange.end, 'end');
  }

  /**
   * ✨ NOVO: Gerenciar mudanças no range de data de vencimento 2
   */
  onDueDateTwoChange(dateRange: DateRange) {
    this.dueDateTwoRange = dateRange;
    const startFieldName = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.startField || 'due_date_two_start';
    const endFieldName = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.endField || 'due_date_two_end';
    
    // Atualizar filtros internos com formato ISO 8601
    this.filters[startFieldName] = DateRangeUtils.formatDateToISO(dateRange.start, 'start');
    this.filters[endFieldName] = DateRangeUtils.formatDateToISO(dateRange.end, 'end');
  }

  /**
   * Aplica os filtros e emite o evento (chamado pelo botão "Aplicar")
   */
  applyFilters() {
    const processedFilters = this.processFilters();
    const apiFilters = this.convertToApiFilters(processedFilters);
    
    // ✅ DEBUG: Log para verificar filtros
    console.log('🔍 [DOMAIN-FILTER] Aplicando filtros:', {
      searchableFields: this.searchableFields.map(f => ({
        field: f.field,
        header: f.header,
        searchType: (f as any).searchType,
        filterField: (f as any).filterField,
        searchField: (f as any).searchField,
        remoteConfig: (f as any).remoteConfig,
        remoteLabel: (f as any).remoteConfig?.label
      })),
      rawFilters: this.filters,
      processedFilters,
      apiFilters
    });
    
    // ✅ NOVO: Incluir defaultFilters no cálculo do badge
    const defaultFiltersCount = this.domainConfig.filterConfig?.defaultFilters?.length || 0;
    const manualFiltersCount = Object.keys(apiFilters).length;
    const totalFiltersForBadge = { ...apiFilters };
    
    // Adicionar defaultFilters ao objeto para o badge (mesmo que não sejam editáveis pelo usuário)
    const defaultFilters = this.domainConfig.filterConfig?.defaultFilters || [];
    defaultFilters.forEach((filter: DefaultFilter) => {
      if (!totalFiltersForBadge[filter.field]) {
        let value = filter.value;
        if (Array.isArray(value)) {
          value = value.join(',');
        }
        totalFiltersForBadge[filter.field] = value;
      }
    });
    
    console.log('🔍 [DEBUG] applyFilters - Badge calculation:', {
      defaultFiltersCount,
      manualFiltersCount,
      totalFiltersForBadge: Object.keys(totalFiltersForBadge).length,
      apiFilters: Object.keys(apiFilters).length
    });
    
    console.log('🔍 [DEBUG] applyFilters - Emitting filtersChanged event with:', totalFiltersForBadge);
    this.filtersChanged.emit(totalFiltersForBadge);
    console.log('🔍 [DEBUG] applyFilters - Event emitted successfully');
  }

  private processFilters(): ProcessedFilters {
    const processed: ProcessedFilters = {};
    
    // ✅ NOVO: Processar defaultFilters primeiro
    const defaultFilters = this.domainConfig.filterConfig?.defaultFilters || [];
    console.log('🔍 [DEBUG] processFilters - defaultFilters:', {
      defaultFilters,
      currentFilters: { ...this.filters }
    });
    
    defaultFilters.forEach((filter: DefaultFilter) => {
      const value = this.filters[filter.field];
      console.log(`🔍 [DEBUG] Processing defaultFilter: ${filter.field} = ${value} (operator: ${filter.operator})`);
      
      if (value !== undefined && value !== null) {
        // Determinar o tipo baseado no operador
        let type: 'simple' | 'multi-select' | 'range' = 'simple';
        if (filter.operator === 'in') {
          type = 'multi-select';
        } else if (filter.operator === 'between') {
          type = 'range';
        }
        
        processed[filter.field] = {
          type: type,
          value: value,
          operator: filter.operator // ✅ Preservar operador para o backend
        };
        
        console.log(`✅ [DEBUG] Added to processed: ${filter.field} =`, processed[filter.field]);
      } else {
        console.log(`⚠️ [DEBUG] Skipped defaultFilter (empty value): ${filter.field} = ${value}`);
      }
    });
    
    this.specialFilters.forEach(filter => {
      if (filter.type === 'date-range') {
        const startValue = this.filters[filter.config.startField];
        const endValue = this.filters[filter.config.endField];
        
        if (startValue || endValue) {
          processed[filter.id] = {
            type: 'date-range',
            start: startValue,
            end: endValue
          };
        }
      }
      
      if (filter.type === 'number-range') {
        const minValue = this.filters[filter.config.startField];
        const maxValue = this.filters[filter.config.endField];
        
        if (minValue || maxValue) {
          processed[filter.id] = {
            type: 'number-range',
            min: minValue,
            max: maxValue
          };
        }
      }
    });
    
    this.searchableFields.forEach(field => {
      // ✅ NOVO: Suporte a filterField, searchField ou field (prioridade nessa ordem)
      const fieldKey = (field as any).filterField || (field as any).searchField || field.field;
      const value = this.filters[fieldKey];
      
      // ✅ NOVO: Tratamento especial para remote-select (arrays)
      if ((field as any).searchType === 'remote-select') {
        if (Array.isArray(value) && value.length > 0) {
          const apiFieldName = (field as any).filterField || (field as any).searchField || field.field;
          processed[apiFieldName] = {
            type: 'multi-select',
            value: value
          };
        }
      } else {
        // ✅ Campos simples (text, number, date)
        if (value && value.toString().trim() !== '') {
          const apiFieldName = (field as any).filterField || (field as any).searchField || field.field;
          processed[apiFieldName] = {
            type: 'simple',
            value: value
          };
        }
      }
    });
    
    // ✅ CORREÇÃO: Verificar se companyIds tem valores válidos
    if (this.showCompanyFilter && this.filters['companyIds'] && 
        Array.isArray(this.filters['companyIds']) && this.filters['companyIds'].length > 0) {
      processed['companyIds'] = {
        type: 'multi-select',
        value: this.filters['companyIds']
      };
    }
    
    // ✅ NOVO: Processar filtros de período (com nomes customizáveis)
    if (this.showDateRangeFilter) {
      // ✅ NOVO: Usar nomes de campos customizados ou padrão
      const startFieldName = this.domainConfig.filterConfig?.dateFieldNames?.startField || 'date_start';
      const endFieldName = this.domainConfig.filterConfig?.dateFieldNames?.endField || 'date_end';
       
      const dateStart = DateRangeUtils.formatDateToISO(this.filters[startFieldName], 'start');
      const dateEnd = DateRangeUtils.formatDateToISO(this.filters[endFieldName], 'end');
      
      // ✅ CORREÇÃO: Só adicionar se as datas não estão vazias
      if (dateStart && dateStart.trim() !== '') {
        processed[startFieldName] = {
          type: 'simple',
          value: dateStart
        };
      }
      if (dateEnd && dateEnd.trim() !== '') {
        processed[endFieldName] = {
          type: 'simple',
          value: dateEnd
        };
      }
    }
    
    // ✨ NOVOS: Processar filtros de data de vencimento
    if (this.showDueDateOneFilter) {
      const dueDateOneStart = this.domainConfig.filterConfig?.dueDateOneFieldNames?.startField || 'due_date_one_start';
      const dueDateOneEnd = this.domainConfig.filterConfig?.dueDateOneFieldNames?.endField || 'due_date_one_end';
      
      const dateStart = DateRangeUtils.formatDateToISO(this.filters[dueDateOneStart], 'start');
      const dateEnd = DateRangeUtils.formatDateToISO(this.filters[dueDateOneEnd], 'end');
      
      if (dateStart && dateStart.trim() !== '') {
        processed[dueDateOneStart] = {
          type: 'simple',
          value: dateStart
        };
      }
      if (dateEnd && dateEnd.trim() !== '') {
        processed[dueDateOneEnd] = {
          type: 'simple',
          value: dateEnd
        };
      }
    }
    
    if (this.showDueDateTwoFilter) {
      const dueDateTwoStart = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.startField || 'due_date_two_start';
      const dueDateTwoEnd = this.domainConfig.filterConfig?.dueDateTwoFieldNames?.endField || 'due_date_two_end';
      
      const dateStart = DateRangeUtils.formatDateToISO(this.filters[dueDateTwoStart], 'start');
      const dateEnd = DateRangeUtils.formatDateToISO(this.filters[dueDateTwoEnd], 'end');
      
      if (dateStart && dateStart.trim() !== '') {
        processed[dueDateTwoStart] = {
          type: 'simple',
          value: dateStart
        };
      }
      if (dateEnd && dateEnd.trim() !== '') {
        processed[dueDateTwoEnd] = {
          type: 'simple',
          value: dateEnd
        };
      }
    }
    
    console.log('🔍 [DEBUG] processFilters - Final processed:', processed);
    return processed;
  }

  private convertToApiFilters(filters: ProcessedFilters): ApiFilters {
    const apiFilters: ApiFilters = {};
    
    console.log('🔍 [DEBUG] convertToApiFilters - Input processed filters:', filters);
    
    Object.entries(filters).forEach(([key, filter]) => {
      console.log(`🔍 [DEBUG] Converting filter: ${key} =`, filter);
      
      switch (filter.type) {
        case 'date-range':
          if (filter.start) {
            apiFilters[`${key}_start`] = filter.start;
            console.log(`✅ [DEBUG] Added date range start: ${key}_start = ${filter.start}`);
          }
          if (filter.end) {
            apiFilters[`${key}_end`] = filter.end;
            console.log(`✅ [DEBUG] Added date range end: ${key}_end = ${filter.end}`);
          }
          break;
          
        case 'number-range':
          if (filter.min) {
            apiFilters[`${key}_min`] = filter.min;
            console.log(`✅ [DEBUG] Added number range min: ${key}_min = ${filter.min}`);
          }
          if (filter.max) {
            apiFilters[`${key}_max`] = filter.max;
            console.log(`✅ [DEBUG] Added number range max: ${key}_max = ${filter.max}`);
          }
          break;
          
        case 'simple':
        case 'multi-select':
        case 'range': // ✅ NOVO: Suporte ao tipo 'range' dos defaultFilters
          apiFilters[key] = filter.value;
          console.log(`✅ [DEBUG] Added ${filter.type}: ${key} = ${filter.value}`);
          break;
          
        default:
          console.warn(`⚠️ [DEBUG] Unknown filter type: ${filter.type} for ${key}`);
      }
    });
    
    console.log('🔍 [DEBUG] convertToApiFilters - Final API filters:', apiFilters);
    return apiFilters;
  }

  clearFilters() {
    // ✅ NOVO: Usar o mesmo método de limpeza (que mantém empresas selecionadas)
    this.clearFiltersOnOpen();
    this.applyDefaultFilters();
    // ✅ NÃO EMITIR AUTOMATICAMENTE. O usuário deve clicar em "Aplicar".
    // this.applyFilters();
  }

  closeFilters() {
    this.visible = false;
    document.body.classList.remove('modal-open'); // ✅ NOVO: Restaurar scroll
    // ✅ NOVO: Limpar filtros ao fechar também (garantir estado limpo)
    this.clearFiltersOnOpen();
    this.visibilityChanged.emit(false);
  }

  hasActiveFilters(): boolean {
    return Object.keys(this.filters).some(key => {
      const value = this.filters[key];
      // ✅ CORREÇÃO: Verificação mais rigorosa para valores vazios
      if (value === null || value === undefined || value === '') {
        return false;
      }
      // ✅ NOVO: Verificar arrays vazios
      if (Array.isArray(value) && value.length === 0) {
        return false;
      }
      // ✅ NOVO: Verificar strings vazias após trim
      if (typeof value === 'string' && value.trim() === '') {
        return false;
      }
      return true;
    });
  }

  getActiveFiltersCount(): number {
    return Object.keys(this.filters).filter(key => {
      const value = this.filters[key];
      // ✅ CORREÇÃO: Usar a mesma lógica do hasActiveFilters()
      if (value === null || value === undefined || value === '') {
        return false;
      }
      if (Array.isArray(value) && value.length === 0) {
        return false;
      }
      if (typeof value === 'string' && value.trim() === '') {
        return false;
      }
      return true;
    }).length;
  }

  /**
   * 🎯 Configura remote-select para filtros (sempre múltiplo)
   */
  getRemoteSelectConfig(field: any): any {
    if (!field.remoteConfig) return null;
    
    // ✅ SEMPRE múltiplo para filtros + configurações otimizadas
    return {
      ...field.remoteConfig,
      multiple: true, // ✅ FORÇAR múltiplo para filtros
      maxResults: field.remoteConfig.maxResults || 50, // ✅ Mais resultados
      placeholder: field.remoteConfig.placeholder || `Selecione ${field.header.toLowerCase()}...`,
      modalTitle: field.remoteConfig.modalTitle || `Selecionar ${field.header}`
    };
  }

} 