import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { FilterService, Filter } from '../../../dashboardnew/common-filter/filter.service';

@Component({
  selector: 'app-compact-filter-runner',
  templateUrl: './compact-filter-runner.component.html',
  styleUrls: ['./compact-filter-runner.component.scss']
})
export class CompactFilterRunnerComponent implements OnInit, OnChanges {
  @Input() filterKey: string = '';
  @Input() filterType: string = 'text';
  @Input() filterOptions: string[] = [];
  @Input() filterLabel: string = '';
  @Input() apiUrl: string = '';
  @Input() connection: number | undefined;
  @Output() filterChange = new EventEmitter<any>();
  
  selectedFilter: Filter | null = null;
  filterValue: any = '';
  availableFilters: Filter[] = [];
  availableKeys: string[] = [];
  availableValues: string[] = [];
  isExpanded: boolean = false; // Add expansion state
  
  constructor(
    private filterService: FilterService
  ) {
    console.log('=== COMPACT FILTER RUNNER CONSTRUCTOR CALLED ===');
  }

  ngOnInit(): void {
    console.log('=== COMPACT FILTER RUNNER DEBUG INFO ===');
    console.log('Component initialized with inputs:');
    console.log('- filterKey:', this.filterKey);
    console.log('- filterType:', this.filterType);
    console.log('- filterOptions:', this.filterOptions);
    console.log('- filterLabel:', this.filterLabel);
    console.log('- apiUrl:', this.apiUrl);
    console.log('- connection:', this.connection);
    console.log('========================================');
    
    // Register this filter with the filter service
    this.registerFilter();
    
    // Subscribe to filter definitions to get available filters
    this.filterService.filters$.subscribe(filters => {
      this.availableFilters = filters;
      console.log('Available filters updated:', filters);
      this.updateSelectedFilter();
    });
    
    // Subscribe to filter state changes
    this.filterService.filterState$.subscribe(state => {
      console.log('Filter state updated:', state);
      if (this.selectedFilter && state.hasOwnProperty(this.selectedFilter.id)) {
        this.filterValue = state[this.selectedFilter.id];
        console.log('Filter value updated for', this.selectedFilter.id, ':', this.filterValue);
      }
    });
  }
  
  ngOnChanges(changes: SimpleChanges): void {
    console.log('=== COMPACT FILTER RUNNER CHANGES DEBUG ===');
    console.log('Component inputs changed:', changes);
    
    // If filterKey or filterType changes, re-register the filter
    if (changes.filterKey || changes.filterType || changes.filterOptions) {
      console.log('Re-registering filter due to input changes');
      this.registerFilter();
    }
    console.log('==========================================');
  }
  
  // Toggle filter expansion
  toggleFilter(): void {
    this.isExpanded = !this.isExpanded;
  }
  
  // Register this filter with the filter service
  registerFilter(): void {
    console.log('Registering filter with key:', this.filterKey, 'type:', this.filterType);
    
    if (this.filterKey) {
      // Get current filter values from the service
      const currentFilterValues = this.filterService.getFilterValues();
      console.log('Current filter values from service:', currentFilterValues);
      
      // Create a filter definition for this compact filter
      const filterDef: Filter = {
        id: `${this.filterKey}`,
        field: this.filterKey,
        label: this.filterLabel || this.filterKey,
        type: this.filterType as any,
        options: this.filterOptions,
        value: this.filterValue // Use the current filter value
      };
      
      console.log('Created filter definition:', filterDef);
      
      // Get current filters
      const currentFilters = this.filterService.getFilters();
      console.log('Current filters from service:', currentFilters);
      
      // Check if this filter is already registered
      const existingFilterIndex = currentFilters.findIndex(f => f.id === filterDef.id);
      console.log('Existing filter index:', existingFilterIndex);
      
      if (existingFilterIndex >= 0) {
        // Preserve the existing filter configuration
        const existingFilter = currentFilters[existingFilterIndex];
        console.log('Found existing filter:', existingFilter);
        
        // Preserve the existing filter value if it exists in the service
        if (currentFilterValues.hasOwnProperty(existingFilter.id)) {
          filterDef.value = currentFilterValues[existingFilter.id];
          this.filterValue = filterDef.value; // Update local value
          console.log('Using value from service:', filterDef.value);
        } else if (existingFilter.value !== undefined) {
          // Fallback to existing filter's value if no service value
          filterDef.value = existingFilter.value;
          this.filterValue = filterDef.value;
          console.log('Using value from existing filter:', filterDef.value);
        }
        
        // Preserve other configuration properties
        filterDef.label = existingFilter.label;
        filterDef.options = existingFilter.options || this.filterOptions;
        
        // Update existing filter
        currentFilters[existingFilterIndex] = filterDef;
        console.log('Updated existing filter:', filterDef);
      } else {
        // For new filters, check if there's already a value in the service
        if (currentFilterValues.hasOwnProperty(filterDef.id)) {
          filterDef.value = currentFilterValues[filterDef.id];
          this.filterValue = filterDef.value; // Update local value
          console.log('Using value from service for new filter:', filterDef.value);
        }
        
        // Add new filter
        currentFilters.push(filterDef);
        console.log('Added new filter:', filterDef);
      }
      
      // Update the filter service with the new filter list
      this.filterService.setFilters(currentFilters);
      
      // Update the selected filter reference
      this.selectedFilter = filterDef;
      console.log('Selected filter set to:', this.selectedFilter);
    } else {
      console.log('No filterKey provided, skipping filter registration');
    }
  }
  
  updateSelectedFilter(): void {
    console.log('Updating selected filter. Filter key:', this.filterKey, 'Available filters:', this.availableFilters);
    if (this.filterKey && this.availableFilters.length > 0) {
      this.selectedFilter = this.availableFilters.find(f => f.field === this.filterKey) || null;
      console.log('Found selected filter:', this.selectedFilter);
      if (this.selectedFilter) {
        // Get current value for this filter from the service
        const currentState = this.filterService.getFilterValues();
        console.log('Current state from service:', currentState);
        const filterValue = currentState[this.selectedFilter.id];
        if (filterValue !== undefined) {
          this.filterValue = filterValue;
        } else if (this.selectedFilter.value !== undefined) {
          // Use the filter's default value if no service value
          this.filterValue = this.selectedFilter.value;
        } else {
          // Use the current filter value as fallback
          this.filterValue = this.filterValue || '';
        }
        
        console.log('Updated selected filter value:', this.filterValue);
      }
    }
  }
  
  onFilterValueChange(value: any): void {
    console.log('Filter value changed:', value);
    
    if (this.selectedFilter) {
      this.filterValue = value;
      this.filterService.updateFilterValue(this.selectedFilter.id, value);
      this.filterChange.emit({ filterId: this.selectedFilter.id, value: value });
      
      // Update the filter definition in the service to reflect the new value
      const currentFilters = this.filterService.getFilters();
      const filterIndex = currentFilters.findIndex(f => f.id === this.selectedFilter.id);
      if (filterIndex >= 0) {
        currentFilters[filterIndex].value = value;
        this.filterService.setFilters(currentFilters);
      }
    }
  }
  
  onToggleChange(checked: boolean): void {
    this.onFilterValueChange(checked);
  }
  
  onDateRangeChange(dateRange: { start: string | null, end: string | null }): void {
    this.onFilterValueChange(dateRange);
  }
  
  // Handle multi-select changes
  onMultiSelectChange(option: string, event: any): void {
    const checked = event.target.checked;
    
    // Initialize filterValue as array if it's not already
    if (!Array.isArray(this.filterValue)) {
      this.filterValue = [];
    }
    
    if (checked) {
      // Add option to array if not already present
      if (!this.filterValue.includes(option)) {
        this.filterValue.push(option);
      }
    } else {
      // Remove option from array
      this.filterValue = this.filterValue.filter((item: string) => item !== option);
    }
    
    // Emit the change
    this.onFilterValueChange(this.filterValue);
  }
  
  // Add method to check if an option is selected for checkboxes (needed for proper UI rendering)
  isOptionSelected(option: string): boolean {
    console.log('Checking if option is selected:', option, 'Current filter value:', this.filterValue);
    if (!this.filterValue) {
      return false;
    }
    
    // Ensure filterValue is an array for multiselect
    if (!Array.isArray(this.filterValue)) {
      this.filterValue = [];
      return false;
    }
    
    return this.filterValue.includes(option);
  }
}