import { Component, OnInit, Input, OnChanges, SimpleChanges, AfterViewChecked, OnDestroy } from '@angular/core';
import { Dashboard3Service } from 'src/app/services/builder/dashboard3.service';
import { FilterService } from '../../common-filter/filter.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-doughnut-chart',
  templateUrl: './doughnut-chart.component.html',
  styleUrls: ['./doughnut-chart.component.scss']
})
export class DoughnutChartComponent implements OnInit, OnChanges, AfterViewChecked, OnDestroy {
  @Input() xAxis: string;
  @Input() yAxis: string | string[];
  @Input() table: string;
  @Input() datastore: string;
  @Input() charttitle: string;
  @Input() chartlegend: boolean = true;
  @Input() showlabel: boolean = true;
  @Input() chartcolor: boolean;
  @Input() slices: boolean;
  @Input() donut: boolean;
  @Input() charturl: string;
  @Input() chartparameter: string;
  @Input() datasource: string;
  @Input() fieldName: string;
  @Input() connection: number; // Add connection input
  // Drilldown configuration inputs
  @Input() drilldownEnabled: boolean = false;
  @Input() drilldownApiUrl: string;
  @Input() drilldownXAxis: string;
  @Input() drilldownYAxis: string;
  @Input() drilldownParameter: string; // Add drilldown parameter input
  @Input() baseFilters: any[] = []; // Add base filters input
  @Input() drilldownFilters: any[] = []; // Add drilldown filters input
  // Multi-layer drilldown configuration inputs
  @Input() drilldownLayers: any[] = []; // Array of drilldown layer configurations

  public doughnutChartLabels: string[] = ["Category A", "Category B", "Category C"];
  public doughnutChartData: any[] = [
    {
      data: [30, 50, 20],
      backgroundColor: [
        '#FF6384',
        '#36A2EB',
        '#FFCE56'
      ],
      hoverBackgroundColor: [
        '#FF6384',
        '#36A2EB',
        '#FFCE56'
      ]
    }
  ];
  public doughnutChartType: string = "doughnut";
  public doughnutChartOptions: any = {
    responsive: true,
    maintainAspectRatio: false,
    cutout: '60%', // This creates the doughnut effect (Chart.js v3+ syntax)
    plugins: {
      legend: {
        display: false // We'll create our own legend
      },
      tooltip: {
        enabled: true,
        mode: 'index',
        intersect: false,
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        titleFont: {
          size: 16,
          color: '#fff'
        },
        bodyFont: {
          size: 14,
          color: '#fff'
        },
        cornerRadius: 4,
        displayColors: false
      }
    },
    animation: {
      animateRotate: true,
      animateScale: false
    },
    elements: {
      arc: {
        borderWidth: 2,
        borderColor: '#fff'
      }
    },
    layout: {
      padding: {
        top: 20,
        bottom: 20,
        left: 20,
        right: 20
      }
    }
  };
  
  // Chart colors for consistent styling
  private chartColors: string[] = [
    '#FF6384',
    '#36A2EB',
    '#FFCE56',
    '#4BC0C0',
    '#9966FF',
    '#FF9F40',
    '#FF6384',
    '#C9CBCF'
  ];
  
  // Multi-layer drilldown state tracking
  drilldownStack: any[] = []; // Stack to track drilldown navigation history
  currentDrilldownLevel: number = 0; // Current drilldown level (0 = base level)
  originalDoughnutChartLabels: string[] = [];
  originalDoughnutChartData: number[] = [];
  
  // No data state
  noDataAvailable: boolean = false;
  
  // Loading state
  isLoading: boolean = false;
  
  // Flag to prevent infinite loops
  private isFetchingData: boolean = false;
  
  // Subscriptions to unsubscribe on destroy
  private subscriptions: Subscription[] = [];

  // Add properties for filter functionality
  private openMultiselects: Map<string, string> = new Map(); // Map of filterId -> context
  private documentClickHandler: ((event: MouseEvent) => void) | null = null;
  private filtersInitialized: boolean = false;

  constructor(
    private dashboardService: Dashboard3Service,
    private filterService: FilterService
  ) { }

  ngOnInit(): void {
    // Subscribe to filter changes
    this.subscriptions.push(
      this.filterService.filterState$.subscribe(filters => {
        // When filters change, refresh the chart data
        this.fetchChartData();
      })
    );
    
    // Validate initial data
    this.validateChartData();
    // Only fetch data if we have the required inputs, otherwise show default data
    if (this.table && this.xAxis && this.yAxis) {
      this.fetchChartData();
    }
  }
  
  /**
   * Validate and sanitize chart data
   */
  private validateChartData(): void {
    // Ensure we have valid arrays
    if (!Array.isArray(this.doughnutChartLabels)) {
      this.doughnutChartLabels = [];
    }
    
    if (!Array.isArray(this.doughnutChartData)) {
      this.doughnutChartData = [];
    }
    
    // Ensure we have some data to display
    if (this.doughnutChartLabels.length === 0 && this.doughnutChartData.length === 0) {
      // Add default data to ensure chart visibility
      this.doughnutChartLabels = ["Category A", "Category B", "Category C"];
      this.doughnutChartData = [
        {
          data: [30, 50, 20],
          backgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
          ],
          hoverBackgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
          ]
        }
      ];
    }
    
    // Ensure we have matching arrays
    if (this.doughnutChartLabels.length !== (this.doughnutChartData[0]?.data?.length || 0)) {
      const maxLength = Math.max(this.doughnutChartLabels.length, this.doughnutChartData[0]?.data?.length || 0);
      while (this.doughnutChartLabels.length < maxLength) {
        this.doughnutChartLabels.push(`Label ${this.doughnutChartLabels.length + 1}`);
      }
      if (this.doughnutChartData[0]) {
        while (this.doughnutChartData[0].data.length < maxLength) {
          this.doughnutChartData[0].data.push(0);
        }
      }
    }
  }
  
  /**
   * Force chart redraw
   */
  public redrawChart(): void {
    // This method can be called to force a chart redraw if needed
    console.log('Redrawing doughnut chart');
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('DoughnutChartComponent input changes:', changes);
    
    // Initialize filter values if they haven't been initialized yet
    if (!this.filtersInitialized && (changes.baseFilters || changes.drilldownFilters || changes.drilldownLayers)) {
      this.initializeFilterValues();
      this.filtersInitialized = true;
    }
    
    // Check if any of the key properties have changed
    const xAxisChanged = changes.xAxis && !changes.xAxis.firstChange;
    const yAxisChanged = changes.yAxis && !changes.yAxis.firstChange;
    const tableChanged = changes.table && !changes.table.firstChange;
    const connectionChanged = changes.connection && !changes.connection.firstChange;
    const baseFiltersChanged = changes.baseFilters && !changes.baseFilters.firstChange;
    const drilldownFiltersChanged = changes.drilldownFilters && !changes.drilldownFilters.firstChange;
    // Drilldown configuration changes
    const drilldownEnabledChanged = changes.drilldownEnabled && !changes.drilldownEnabled.firstChange;
    const drilldownApiUrlChanged = changes.drilldownApiUrl && !changes.drilldownApiUrl.firstChange;
    const drilldownXAxisChanged = changes.drilldownXAxis && !changes.drilldownXAxis.firstChange;
    const drilldownYAxisChanged = changes.drilldownYAxis && !changes.drilldownYAxis.firstChange;
    const drilldownLayersChanged = changes.drilldownLayers && !changes.drilldownLayers.firstChange;
    
    // Only fetch data if the actual chart configuration changed and we're not already fetching
    if (!this.isFetchingData && (xAxisChanged || yAxisChanged || tableChanged || connectionChanged || baseFiltersChanged || drilldownFiltersChanged ||
        drilldownEnabledChanged || drilldownApiUrlChanged || drilldownXAxisChanged || drilldownYAxisChanged ||
        drilldownLayersChanged)) {
      console.log('Chart configuration changed, fetching new data');
      this.fetchChartData();
    }
    
    // If we have the required inputs and haven't fetched data yet, fetch it
    if ((xAxisChanged || yAxisChanged || tableChanged) && this.table && this.xAxis && this.yAxis && !this.isFetchingData) {
      console.log('Required inputs available, fetching data');
      this.fetchChartData();
    }
  }
  
  ngAfterViewChecked() {
    // Debugging: Log component state after view checks
    console.log('DoughnutChartComponent state:', {
      labels: this.doughnutChartLabels,
      data: this.doughnutChartData,
      hasData: this.doughnutChartLabels.length > 0 && this.doughnutChartData.length > 0
    });
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(sub => sub.unsubscribe());
    // Clean up document click handler
    this.removeDocumentClickHandler();
  }
  
  // Initialize filter values with proper default values based on type
  private initializeFilterValues(): void {
    console.log('Initializing filter values');
    
    // Initialize base filters
    if (this.baseFilters) {
      this.baseFilters.forEach(filter => {
        if (filter.value === undefined || filter.value === null) {
          switch (filter.type) {
            case 'multiselect':
              filter.value = [];
              break;
            case 'date-range':
              filter.value = { start: null, end: null };
              break;
            case 'toggle':
              filter.value = false;
              break;
            default:
              filter.value = '';
          }
        }
      });
    }
    
    // Initialize drilldown filters
    if (this.drilldownFilters) {
      this.drilldownFilters.forEach(filter => {
        if (filter.value === undefined || filter.value === null) {
          switch (filter.type) {
            case 'multiselect':
              filter.value = [];
              break;
            case 'date-range':
              filter.value = { start: null, end: null };
              break;
            case 'toggle':
              filter.value = false;
              break;
            default:
              filter.value = '';
          }
        }
      });
    }
    
    // Initialize layer filters
    if (this.drilldownLayers) {
      this.drilldownLayers.forEach(layer => {
        if (layer.filters) {
          layer.filters.forEach((filter: any) => {
            if (filter.value === undefined || filter.value === null) {
              switch (filter.type) {
                case 'multiselect':
                  filter.value = [];
                  break;
                case 'date-range':
                  filter.value = { start: null, end: null };
                  break;
                case 'toggle':
                  filter.value = false;
                  break;
                default:
                  filter.value = '';
              }
            }
          });
        }
      });
    }
    
    console.log('Filter values initialized:', {
      baseFilters: this.baseFilters,
      drilldownFilters: this.drilldownFilters,
      drilldownLayers: this.drilldownLayers
    });
  }

  // Check if there are active filters
  hasActiveFilters(): boolean {
    return (this.baseFilters && this.baseFilters.length > 0) || 
           (this.drilldownFilters && this.drilldownFilters.length > 0) || 
           this.hasActiveLayerFilters();
  }

  // Check if there are active layer filters for current drilldown level
  hasActiveLayerFilters(): boolean {
    if (this.currentDrilldownLevel > 1 && this.drilldownLayers && this.drilldownLayers.length > 0) {
      const layerIndex = this.currentDrilldownLevel - 2; // -2 because level 1 is base drilldown
      return layerIndex < this.drilldownLayers.length && 
             this.drilldownLayers[layerIndex].filters && 
             this.drilldownLayers[layerIndex].filters.length > 0;
    }
    return false;
  }

  // Get active layer filters for current drilldown level
  getActiveLayerFilters(): any[] {
    if (this.currentDrilldownLevel > 1 && this.drilldownLayers && this.drilldownLayers.length > 0) {
      const layerIndex = this.currentDrilldownLevel - 2; // -2 because level 1 is base drilldown
      if (layerIndex < this.drilldownLayers.length && 
          this.drilldownLayers[layerIndex].filters) {
        return this.drilldownLayers[layerIndex].filters;
      }
    }
    return [];
  }

  // Get filter options for dropdown/multiselect filters
  getFilterOptions(filter: any): string[] {
    if (filter.options) {
      if (Array.isArray(filter.options)) {
        return filter.options;
      } else if (typeof filter.options === 'string') {
        return filter.options.split(',').map(opt => opt.trim()).filter(opt => opt);
      }
    }
    return [];
  }

  // Check if an option is selected for multiselect filters
  isOptionSelected(filter: any, option: string): boolean {
    if (!filter.value) {
      return false;
    }
    
    if (Array.isArray(filter.value)) {
      return filter.value.includes(option);
    }
    
    return filter.value === option;
  }

  // Handle base filter changes
  onBaseFilterChange(filter: any): void {
    console.log('Base filter changed:', filter);
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Handle drilldown filter changes
  onDrilldownFilterChange(filter: any): void {
    console.log('Drilldown filter changed:', filter);
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Handle layer filter changes
  onLayerFilterChange(filter: any): void {
    console.log('Layer filter changed:', filter);
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Handle multiselect changes
  onMultiSelectChange(filter: any, option: string, event: any): void {
    const checked = event.target.checked;
    
    // Initialize filter.value as array if it's not already
    if (!Array.isArray(filter.value)) {
      filter.value = [];
    }
    
    if (checked) {
      // Add option to array if not already present
      if (!filter.value.includes(option)) {
        filter.value.push(option);
      }
    } else {
      // Remove option from array
      filter.value = filter.value.filter((item: string) => item !== option);
    }
    
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Handle date range changes
  onDateRangeChange(filter: any, dateRange: { start: string | null, end: string | null }): void {
    filter.value = dateRange;
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Handle toggle changes
  onToggleChange(filter: any, checked: boolean): void {
    filter.value = checked;
    // Refresh data when filter changes
    this.fetchChartData();
  }

  // Toggle multiselect dropdown visibility
  toggleMultiselect(filter: any, context: string): void {
    const filterId = `${context}-${filter.field}`;
    if (this.isMultiselectOpen(filter, context)) {
      this.openMultiselects.delete(filterId);
    } else {
      // Close all other multiselects first
      this.openMultiselects.clear();
      this.openMultiselects.set(filterId, context);
      
      // Add document click handler to close dropdown when clicking outside
      this.addDocumentClickHandler();
    }
  }

  // Add document click handler to close dropdowns when clicking outside
  private addDocumentClickHandler(): void {
    if (!this.documentClickHandler) {
      this.documentClickHandler = (event: MouseEvent) => {
        const target = event.target as HTMLElement;
        // Check if click is outside any multiselect dropdown
        if (!target.closest('.multiselect-container')) {
          this.openMultiselects.clear();
          this.removeDocumentClickHandler();
        }
      };
      
      // Use setTimeout to ensure the click event that opened the dropdown doesn't immediately close it
      setTimeout(() => {
        document.addEventListener('click', this.documentClickHandler!);
      }, 0);
    }
  }

  // Remove document click handler
  private removeDocumentClickHandler(): void {
    if (this.documentClickHandler) {
      document.removeEventListener('click', this.documentClickHandler);
      this.documentClickHandler = null;
    }
  }

  // Check if multiselect dropdown is open
  isMultiselectOpen(filter: any, context: string): boolean {
    const filterId = `${context}-${filter.field}`;
    return this.openMultiselects.has(filterId);
  }

  // Get count of selected options for a multiselect filter
  getSelectedOptionsCount(filter: any): number {
    if (!filter.value) {
      return 0;
    }
    
    if (Array.isArray(filter.value)) {
      return filter.value.length;
    }
    
    return 0;
  }

  // Clear all filters
  clearAllFilters(): void {
    // Clear base filters
    if (this.baseFilters) {
      this.baseFilters.forEach(filter => {
        if (filter.type === 'multiselect') {
          filter.value = [];
        } else if (filter.type === 'date-range') {
          filter.value = { start: null, end: null };
        } else if (filter.type === 'toggle') {
          filter.value = false;
        } else {
          filter.value = '';
        }
      });
    }
    
    // Clear drilldown filters
    if (this.drilldownFilters) {
      this.drilldownFilters.forEach(filter => {
        if (filter.type === 'multiselect') {
          filter.value = [];
        } else if (filter.type === 'date-range') {
          filter.value = { start: null, end: null };
        } else if (filter.type === 'toggle') {
          filter.value = false;
        } else {
          filter.value = '';
        }
      });
    }
    
    // Clear layer filters
    if (this.drilldownLayers) {
      this.drilldownLayers.forEach(layer => {
        if (layer.filters) {
          layer.filters.forEach((filter: any) => {
            if (filter.type === 'multiselect') {
              filter.value = [];
            } else if (filter.type === 'date-range') {
              filter.value = { start: null, end: null };
            } else if (filter.type === 'toggle') {
              filter.value = false;
            } else {
              filter.value = '';
            }
          });
        }
      });
    }
    
    // Close all multiselect dropdowns
    this.openMultiselects.clear();
    
    // Refresh data
    this.fetchChartData();
  }
  
  // Public method to refresh data when filters change
  refreshData(): void {
    this.fetchChartData();
  }
  
  fetchChartData(): void {
    // Set loading state
    this.isLoading = true;
    
    // Set flag to prevent recursive calls
    this.isFetchingData = true;
    
    // If we're in drilldown mode, fetch the appropriate drilldown data
    if (this.currentDrilldownLevel > 0 && this.drilldownStack.length > 0) {
      this.fetchDrilldownData();
      // Reset flags after fetching
      this.isFetchingData = false;
      this.isLoading = false;
      return;
    }
    
    // If we have the necessary data, fetch chart data from the service
    if (this.table && this.xAxis && this.yAxis) {
      console.log('Fetching doughnut chart data for:', { table: this.table, xAxis: this.xAxis, yAxis: this.yAxis, connection: this.connection });
      
      // Convert yAxis to string if it's an array
      const yAxisString = Array.isArray(this.yAxis) ? this.yAxis.join(',') : this.yAxis;
      
      // Convert baseFilters to filter parameters
      let filterParams = '';
      if (this.baseFilters && this.baseFilters.length > 0) {
        const filterObj = {};
        this.baseFilters.forEach(filter => {
          if (filter.field && filter.value) {
            filterObj[filter.field] = filter.value;
          }
        });
        if (Object.keys(filterObj).length > 0) {
          filterParams = JSON.stringify(filterObj);
        }
      }
      
      // Add common filters to filter parameters
      const commonFilters = this.filterService.getFilterValues();
      console.log('Common filters from service:', commonFilters);
      
      if (Object.keys(commonFilters).length > 0) {
        // Merge common filters with base filters
        const mergedFilterObj = {};
        
        // Add base filters first
        if (filterParams) {
          try {
            const baseFilterObj = JSON.parse(filterParams);
            Object.assign(mergedFilterObj, baseFilterObj);
          } catch (e) {
            console.warn('Failed to parse base filter parameters:', e);
          }
        }
        
        // Add common filters using the field name as the key, not the filter id
        Object.keys(commonFilters).forEach(filterId => {
          const filterValue = commonFilters[filterId];
          // Find the filter definition to get the field name
          const filterDef = this.filterService.getFilters().find(f => f.id === filterId);
          if (filterDef && filterDef.field) {
            const fieldName = filterDef.field;
            if (filterValue !== undefined && filterValue !== null && filterValue !== '') {
              mergedFilterObj[fieldName] = filterValue;
            }
          } else {
            // Fallback to using filterId as field name if no field is defined
            if (filterValue !== undefined && filterValue !== null && filterValue !== '') {
              mergedFilterObj[filterId] = filterValue;
            }
          }
        });
        
        if (Object.keys(mergedFilterObj).length > 0) {
          filterParams = JSON.stringify(mergedFilterObj);
        }
      }
      
      console.log('Final filter parameters:', filterParams);
      
      // Log the URL that will be called
      const url = `chart/getdashjson/doughnut?tableName=${this.table}&xAxis=${this.xAxis}&yAxes=${yAxisString}${this.connection ? `&sureId=${this.connection}` : ''}`;
      console.log('Chart data URL:', url);
      
      // Fetch data from the dashboard service with parameter field and value
      // For base level, we pass empty parameter and value, but now also pass filters
      this.dashboardService.getChartData(this.table, 'doughnut', this.xAxis, yAxisString, this.connection, '', '', filterParams).subscribe(
        (data: any) => {
          console.log('Received doughnut chart data:', data);
          if (data === null) {
            console.warn('API returned null data. Check if the API endpoint is working correctly.');
            this.noDataAvailable = true;
            this.doughnutChartLabels = [];
            this.doughnutChartData = [];
            // Reset flags after fetching
            this.isFetchingData = false;
            this.isLoading = false;
            return;
          }
          
          // Handle the actual data structure returned by the API
          if (data && data.chartLabels && data.chartData) {
            // Backend has already filtered the data, just display it
            this.noDataAvailable = data.chartLabels.length === 0;
            this.doughnutChartLabels = data.chartLabels;
            
            // Handle different data structures
            let chartDataValues;
            if (Array.isArray(data.chartData)) {
              // If chartData is already an array of values
              if (data.chartData.length > 0 && typeof data.chartData[0] !== 'object') {
                chartDataValues = data.chartData;
              } 
              // If chartData is an array with one object containing the data
              else if (data.chartData.length > 0 && data.chartData[0].data) {
                chartDataValues = data.chartData[0].data;
              }
              // Default case
              else {
                chartDataValues = data.chartData;
              }
            } else {
              chartDataValues = [data.chartData];
            }
            
            this.doughnutChartData = [
              {
                data: chartDataValues,
                backgroundColor: this.chartColors.slice(0, chartDataValues.length),
                hoverBackgroundColor: this.chartColors.slice(0, chartDataValues.length)
              }
            ];
            console.log('Updated doughnut chart with data:', { labels: this.doughnutChartLabels, data: this.doughnutChartData });
          } else if (data && data.labels && data.datasets) {
            // Backend has already filtered the data, just display it
            this.noDataAvailable = data.labels.length === 0;
            this.doughnutChartLabels = data.labels;
            this.doughnutChartData = data.datasets;
            console.log('Updated doughnut chart with legacy data format:', { labels: this.doughnutChartLabels, data: this.doughnutChartData });
          } else {
            console.warn('Received data does not have expected structure', data);
            this.noDataAvailable = true;
            // Keep default data instead of empty arrays
            this.doughnutChartLabels = ["Category A", "Category B", "Category C"];
            this.doughnutChartData = [
              {
                data: [30, 50, 20],
                backgroundColor: [
                  '#FF6384',
                  '#36A2EB',
                  '#FFCE56'
                ],
                hoverBackgroundColor: [
                  '#FF6384',
                  '#36A2EB',
                  '#FFCE56'
                ]
              }
            ];
          }
          // Reset flags after fetching
          this.isFetchingData = false;
          this.isLoading = false;
        },
        (error) => {
          console.error('Error fetching doughnut chart data:', error);
          this.noDataAvailable = true;
          // Keep default data in case of error
          this.doughnutChartLabels = ["Category A", "Category B", "Category C"];
          this.doughnutChartData = [
            {
              data: [30, 50, 20],
              backgroundColor: [
                '#FF6384',
                '#36A2EB',
                '#FFCE56'
              ],
              hoverBackgroundColor: [
                '#FF6384',
                '#36A2EB',
                '#FFCE56'
              ]
            }
          ];
          // Reset flags after fetching
          this.isFetchingData = false;
          this.isLoading = false;
        }
      );
    } else {
      console.log('Missing required data for chart:', { table: this.table, xAxis: this.xAxis, yAxis: this.yAxis, connection: this.connection });
      this.noDataAvailable = true;
      this.doughnutChartLabels = [];
      this.doughnutChartData = [];
      // Reset flags after fetching
      this.isFetchingData = false;
      this.isLoading = false;
    }
  }
  
  // Fetch drilldown data based on current drilldown level
  fetchDrilldownData(): void {
    console.log('Fetching drilldown data, current level:', this.currentDrilldownLevel);
    console.log('Drilldown stack:', this.drilldownStack);
    
    // Get the current drilldown configuration based on the current level
    let drilldownConfig;
    if (this.currentDrilldownLevel === 1) {
      // Base drilldown level
      drilldownConfig = {
        apiUrl: this.drilldownApiUrl,
        xAxis: this.drilldownXAxis,
        yAxis: this.drilldownYAxis,
        parameter: this.drilldownParameter
      };
    } else {
      // Multi-layer drilldown level
      const layerIndex = this.currentDrilldownLevel - 2; // -2 because level 1 is base drilldown
      if (layerIndex >= 0 && layerIndex < this.drilldownLayers.length) {
        drilldownConfig = this.drilldownLayers[layerIndex];
      } else {
        console.warn('Invalid drilldown layer index:', layerIndex);
        this.noDataAvailable = true;
        this.doughnutChartLabels = [];
        this.doughnutChartData = [];
        return;
      }
    }
    
    console.log('Drilldown config for level', this.currentDrilldownLevel, ':', drilldownConfig);
    
    // Check if we have valid drilldown configuration
    if (!drilldownConfig || !drilldownConfig.apiUrl || !drilldownConfig.xAxis || !drilldownConfig.yAxis) {
      console.warn('Missing drilldown configuration for level:', this.currentDrilldownLevel);
      this.noDataAvailable = true;
      this.doughnutChartLabels = [];
      this.doughnutChartData = [];
      return;
    }
    
    // Get the parameter value from the drilldown stack
    let parameterValue = '';
    if (this.drilldownStack.length > 0) {
      const lastEntry = this.drilldownStack[this.drilldownStack.length - 1];
      parameterValue = lastEntry.clickedValue || '';
      console.log('Parameter value from last click:', parameterValue);
    }
    
    // Get the parameter field from drilldown config
    const parameterField = drilldownConfig.parameter || '';
    console.log('Parameter field:', parameterField);
    
    console.log('Fetching drilldown data for level:', this.currentDrilldownLevel, {
      apiUrl: drilldownConfig.apiUrl,
      xAxis: drilldownConfig.xAxis,
      yAxis: drilldownConfig.yAxis,
      parameterField: parameterField,
      parameterValue: parameterValue,
      connection: this.connection
    });
    
    // Build the actual API URL with parameter replacement
    let actualApiUrl = drilldownConfig.apiUrl;
    console.log('Original API URL:', actualApiUrl);
    console.log('Parameter value to use:', parameterValue);
    console.log('Parameter field:', parameterField);
    
    // Check if the URL contains angle brackets for parameter replacement
    const hasAngleBrackets = /<[^>]+>/.test(actualApiUrl);
    
    if (hasAngleBrackets && parameterValue) {
      // Replace angle brackets placeholder with actual value
      console.log('Replacing angle brackets with parameter value');
      const encodedValue = encodeURIComponent(parameterValue);
      actualApiUrl = actualApiUrl.replace(/<[^>]+>/g, encodedValue);
      console.log('URL after angle bracket replacement:', actualApiUrl);
    }
    
    // Convert drilldown layer filters to filter parameters (if applicable)
    let filterParams = '';
    if (drilldownConfig.filters && drilldownConfig.filters.length > 0) {
      const filterObj = {};
      drilldownConfig.filters.forEach((filter: any) => {
        if (filter.field && filter.value) {
          filterObj[filter.field] = filter.value;
        }
      });
      if (Object.keys(filterObj).length > 0) {
        filterParams = JSON.stringify(filterObj);
      }
    }
    
    // Add common filters to drilldown filter parameters
    const commonFilters = this.filterService.getFilterValues();
    if (Object.keys(commonFilters).length > 0) {
      // Merge common filters with drilldown filters
      const mergedFilterObj = {};
      
      // Add drilldown filters first
      if (filterParams) {
        try {
          const drilldownFilterObj = JSON.parse(filterParams);
          Object.assign(mergedFilterObj, drilldownFilterObj);
        } catch (e) {
          console.warn('Failed to parse drilldown filter parameters:', e);
        }
      }
      
      // Add common filters
      Object.keys(commonFilters).forEach(key => {
        const value = commonFilters[key];
        if (value !== undefined && value !== null && value !== '') {
          mergedFilterObj[key] = value;
        }
      });
      
      if (Object.keys(mergedFilterObj).length > 0) {
        filterParams = JSON.stringify(mergedFilterObj);
      }
    }
    
    // Log the URL that will be called
    const url = `chart/getdashjson/doughnut?tableName=${actualApiUrl}&xAxis=${drilldownConfig.xAxis}&yAxes=${drilldownConfig.yAxis}${this.connection ? `&sureId=${this.connection}` : ''}`;
    console.log('Drilldown data URL:', url);
    
    // Fetch data from the dashboard service with parameter field and value
    // Backend handles filtering, we just pass the parameter field and value
    this.dashboardService.getChartData(actualApiUrl, 'doughnut', drilldownConfig.xAxis, drilldownConfig.yAxis, this.connection, parameterField, parameterValue, filterParams).subscribe(
      (data: any) => {
        console.log('Received drilldown data:', data);
        if (data === null) {
          console.warn('Drilldown API returned null data. Check if the API endpoint is working correctly.');
          this.noDataAvailable = true;
          this.doughnutChartLabels = [];
          this.doughnutChartData = [];
          return;
        }
        
        // Handle the actual data structure returned by the API
        if (data && data.chartLabels && data.chartData) {
          // Backend has already filtered the data, just display it
          this.noDataAvailable = data.chartLabels.length === 0;
          this.doughnutChartLabels = data.chartLabels;
          
          // Handle different data structures
          let chartDataValues;
          if (Array.isArray(data.chartData)) {
            // If chartData is already an array of values
            if (data.chartData.length > 0 && typeof data.chartData[0] !== 'object') {
              chartDataValues = data.chartData;
            } 
            // If chartData is an array with one object containing the data
            else if (data.chartData.length > 0 && data.chartData[0].data) {
              chartDataValues = data.chartData[0].data;
            }
            // Default case
            else {
              chartDataValues = data.chartData;
            }
          } else {
            chartDataValues = [data.chartData];
          }
          
          this.doughnutChartData = [
            {
              data: chartDataValues,
              backgroundColor: this.chartColors.slice(0, chartDataValues.length),
              hoverBackgroundColor: this.chartColors.slice(0, chartDataValues.length)
            }
          ];
          console.log('Updated doughnut chart with drilldown data:', { labels: this.doughnutChartLabels, data: this.doughnutChartData });
          // Set loading state to false
          this.isLoading = false;
        } else if (data && data.labels && data.datasets) {
          // Backend has already filtered the data, just display it
          this.noDataAvailable = data.labels.length === 0;
          this.doughnutChartLabels = data.labels;
          this.doughnutChartData = data.datasets;
          console.log('Updated doughnut chart with drilldown legacy data format:', { labels: this.doughnutChartLabels, data: this.doughnutChartData });
          // Set loading state to false
          this.isLoading = false;
        } else {
          console.warn('Drilldown received data does not have expected structure', data);
          this.noDataAvailable = true;
          // Keep current data instead of empty arrays
          // Set loading state to false
          this.isLoading = false;
        }
      },
      (error) => {
        console.error('Error fetching drilldown data:', error);
        this.noDataAvailable = true;
        // Keep current data in case of error
        // Set loading state to false
        this.isLoading = false;
      }
    );
    
    // Set loading state
    this.isLoading = true;
  }
  
  // Reset to original data (go back to base level)
  resetToOriginalData(): void {
    console.log('Resetting to original data');
    console.log('Current stack before reset:', this.drilldownStack);
    console.log('Current level before reset:', this.currentDrilldownLevel);
    
    this.currentDrilldownLevel = 0;
    this.drilldownStack = [];
    
    if (this.originalDoughnutChartLabels.length > 0) {
      this.doughnutChartLabels = [...this.originalDoughnutChartLabels];
      console.log('Restored original labels');
    }
    if (this.originalDoughnutChartData.length > 0) {
      this.doughnutChartData = JSON.parse(JSON.stringify(this.originalDoughnutChartData));
      console.log('Restored original data');
    }
    
    console.log('After reset - labels:', this.doughnutChartLabels);
    console.log('After reset - data:', this.doughnutChartData);
    
    // Re-fetch original data
    this.fetchChartData();
  }

  // Navigate back to previous drilldown level
  navigateBack(): void {
    console.log('Navigating back, current stack:', this.drilldownStack);
    console.log('Current level:', this.currentDrilldownLevel);
    
    if (this.drilldownStack.length > 0) {
      // Remove the last entry from the stack
      const removedEntry = this.drilldownStack.pop();
      console.log('Removed entry from stack:', removedEntry);
      
      // Update the current drilldown level
      this.currentDrilldownLevel = this.drilldownStack.length;
      console.log('New level after pop:', this.currentDrilldownLevel);
      console.log('Stack after pop:', this.drilldownStack);
      
      if (this.drilldownStack.length > 0) {
        // Fetch data for the previous level
        console.log('Fetching data for previous level');
        this.fetchDrilldownData();
      } else {
        // Back to base level
        console.log('Back to base level, resetting to original data');
        this.resetToOriginalData();
      }
    } else {
      // Already at base level, reset to original data
      console.log('Already at base level, resetting to original data');
      this.resetToOriginalData();
    }
  }

  // Get legend color for a specific index
  getLegendColor(index: number): string {
    return this.chartColors[index % this.chartColors.length];
  }

  // events
  public chartClicked(e: any): void {
    console.log('Doughnut chart clicked:', e);
    
    // If drilldown is enabled and we have a valid click event
    if (this.drilldownEnabled && e.active && e.active.length > 0) {
      // Get the index of the clicked element
      const clickedIndex = e.active[0].index;
      
      // Get the label of the clicked element
      const clickedLabel = this.doughnutChartLabels[clickedIndex];
      
      console.log('Clicked on doughnut slice:', { index: clickedIndex, label: clickedLabel });
      
      // If we're not at the base level, store original data
      if (this.currentDrilldownLevel === 0) {
        // Store original data before entering drilldown mode
        this.originalDoughnutChartLabels = [...this.doughnutChartLabels];
        this.originalDoughnutChartData = [...this.doughnutChartData];
        console.log('Stored original data for drilldown');
      }
      
      // Determine the next drilldown level
      const nextDrilldownLevel = this.currentDrilldownLevel + 1;
      
      console.log('Next drilldown level will be:', nextDrilldownLevel);
      
      // Check if there's a drilldown configuration for this level
      let hasDrilldownConfig = false;
      let drilldownConfig;
      
      if (nextDrilldownLevel === 1) {
        // Base drilldown level
        drilldownConfig = {
          apiUrl: this.drilldownApiUrl,
          xAxis: this.drilldownXAxis,
          yAxis: this.drilldownYAxis,
          parameter: this.drilldownParameter
        };
        hasDrilldownConfig = !!this.drilldownApiUrl && !!this.drilldownXAxis && !!this.drilldownYAxis;
      } else {
        // Multi-layer drilldown level
        const layerIndex = nextDrilldownLevel - 2; // -2 because level 1 is base drilldown
        if (layerIndex < this.drilldownLayers.length) {
          drilldownConfig = this.drilldownLayers[layerIndex];
          hasDrilldownConfig = drilldownConfig.enabled &&
                              !!drilldownConfig.apiUrl && 
                              !!drilldownConfig.xAxis && 
                              !!drilldownConfig.yAxis;
        }
      }
      
      console.log('Drilldown config for next level:', drilldownConfig);
      console.log('Has drilldown config:', hasDrilldownConfig);
      
      // If there's a drilldown configuration for the next level, proceed
      if (hasDrilldownConfig) {
        // Add this click to the drilldown stack
        const stackEntry = {
          level: nextDrilldownLevel,
          clickedIndex: clickedIndex,
          clickedLabel: clickedLabel,
          clickedValue: clickedLabel // Using label as value for now
        };
        
        this.drilldownStack.push(stackEntry);
        
        console.log('Added to drilldown stack:', stackEntry);
        console.log('Current drilldown stack:', this.drilldownStack);
        
        // Update the current drilldown level
        this.currentDrilldownLevel = nextDrilldownLevel;
        
        console.log('Entering drilldown level:', this.currentDrilldownLevel);
        
        // Fetch drilldown data for the new level
        this.fetchDrilldownData();
      } else {
        console.log('No drilldown configuration for level:', nextDrilldownLevel);
      }
    } else {
      console.log('Drilldown not enabled or invalid click event');
    }
  }

  public chartHovered(e: any): void {
    console.log('Doughnut chart hovered:', e);
  }
}