import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges, ViewChild } from '@angular/core';
import { Dashboard3Service } from '../../../../../../services/builder/dashboard3.service';
import { Subscription } from 'rxjs';
import { FilterService } from '../../common-filter/filter.service';
// Add BaseChartDirective import for chart resizing
import { BaseChartDirective } from 'ng2-charts';

@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnInit, OnChanges, 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

  // Add ViewChild to access the chart directive
  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;

  barChartLabels: string[] = ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'];
  barChartType: string = 'bar';
  barChartPlugins = [];
  barChartData: any[] = [
    { data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }
  ];
  barChartLegend: boolean = true;
  
  // Add responsive chart options
  barChartOptions: any = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        ticks: {
          autoSkip: false,
          maxRotation: 45,
          minRotation: 45
        }
      },
      y: {
        beginAtZero: true
      }
    },
    plugins: {
      legend: {
        display: true,
        position: 'top',
      },
      tooltip: {
        enabled: true
      }
    }
  };
  
  // Multi-layer drilldown state tracking
  drilldownStack: any[] = []; // Stack to track drilldown navigation history
  currentDrilldownLevel: number = 0; // Current drilldown level (0 = base level)
  originalBarChartLabels: string[] = [];
  originalBarChartData: any[] = [];
  
  // No data state
  noDataAvailable: boolean = false;
  
  // Flag to prevent infinite loops
  private isFetchingData: boolean = false;
  
  // Subscriptions to unsubscribe on destroy
  private subscriptions: Subscription[] = [];

  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();
      })
    );
    
    // Initialize with default data
    this.fetchChartData();
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('BarChartComponent input changes:', changes);
    
    // 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();
    }
    
    // Update legend visibility if it changed
    if (changes.chartlegend !== undefined) {
      this.barChartLegend = changes.chartlegend.currentValue;
      this.barChartOptions.plugins.legend.display = this.barChartLegend;
      console.log('Chart legend changed to:', this.barChartLegend);
    }
  }

  fetchChartData(): void {
    // 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 flag after fetching
      this.isFetchingData = false;
      return;
    }
    
    // If we have the necessary data, fetch chart data from the service
    if (this.table && this.xAxis && this.yAxis) {
      console.log('=== BAR CHART DEBUG INFO ===');
      console.log('Table:', this.table);
      console.log('X-Axis:', this.xAxis);
      console.log('Y-Axis:', this.yAxis);
      console.log('Connection:', this.connection);
      
      // Convert yAxis to string if it's an array
      const yAxisString = Array.isArray(this.yAxis) ? this.yAxis.join(',') : this.yAxis;
      console.log('Y-Axis String:', yAxisString);
      
      // Get the parameter value from the drilldown stack for base level (should be empty)
      let parameterValue = '';
      
      // Log the URL that will be called
      let url = `chart/getdashjson/bar?tableName=${this.table}&xAxis=${this.xAxis}&yAxes=${yAxisString}${this.connection ? `&sureId=${this.connection}` : ''}`;
      console.log('Bar chart data URL:', url);
      
      // 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);
        }
      }
      console.log('Base filters:', this.baseFilters);
      console.log('Base filter params:', filterParams);
      
      // Add common filters to filter parameters
      const commonFilters = this.filterService.getFilterValues();
      const filterDefinitions = this.filterService.getFilters();
      console.log('Common filters from service:', commonFilters);
      console.log('Filter definitions:', filterDefinitions);
      
      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];
          console.log(`Processing filter ID: ${filterId}, Value:`, filterValue);
          
          // Find the filter definition to get the field name
          const filterDef = this.filterService.getFilters().find(f => f.id === filterId);
          console.log(`Filter definition for ${filterId}:`, filterDef);
          
          if (filterDef && filterDef.field) {
            const fieldName = filterDef.field;
            console.log(`Mapping filter ID ${filterId} to field name: ${fieldName}`);
            if (filterValue !== undefined && filterValue !== null && filterValue !== '') {
              mergedFilterObj[fieldName] = filterValue;
              console.log(`Added to merged filters: ${fieldName} =`, filterValue);
            }
          } else {
            // Fallback to using filterId as field name if no field is defined
            console.log(`No field name found for filter ID ${filterId}, using ID as field name`);
            if (filterValue !== undefined && filterValue !== null && filterValue !== '') {
              mergedFilterObj[filterId] = filterValue;
              console.log(`Added to merged filters: ${filterId} =`, filterValue);
            }
          }
        });
        
        if (Object.keys(mergedFilterObj).length > 0) {
          filterParams = JSON.stringify(mergedFilterObj);
        }
      }
      
      console.log('Final merged filter object:', filterParams);
      // 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
      const subscription = this.dashboardService.getChartData(this.table, 'bar', this.xAxis, yAxisString, this.connection, '', '', filterParams).subscribe(
        (data: any) => {
          console.log('=== BAR CHART DATA RESPONSE ===');
          console.log('Received bar chart data:', data);
          if (data === null) {
            console.warn('Bar chart API returned null data. Check if the API endpoint is working correctly.');
            this.noDataAvailable = true;
            this.barChartLabels = [];
            this.barChartData = [];
            // Reset flag after fetching
            this.isFetchingData = 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.barChartLabels = data.chartLabels;
            this.barChartData = data.chartData;
            // Trigger change detection
            // this.barChartData = [...this.barChartData];
            console.log('Updated bar chart with data:', { labels: this.barChartLabels, data: this.barChartData });
            console.log('=== CHART UPDATED SUCCESSFULLY ===');
          } else if (data && data.labels && data.datasets) {
            // Backend has already filtered the data, just display it
            this.noDataAvailable = data.labels.length === 0;
            this.barChartLabels = data.labels;
            this.barChartData = data.datasets;
            // Trigger change detection
            // this.barChartData = [...this.barChartData];
            console.log('Updated bar chart with legacy data format:', { labels: this.barChartLabels, data: this.barChartData });
            console.log('=== CHART UPDATED SUCCESSFULLY (LEGACY) ===');
          } else {
            console.warn('Bar chart received data does not have expected structure', data);
            this.noDataAvailable = true;
            this.barChartLabels = [];
            this.barChartData = [];
          }
          // Reset flag after fetching
          this.isFetchingData = false;
        },
        (error) => {
          console.error('=== BAR CHART ERROR ===');
          console.error('Error fetching bar chart data:', error);
          this.noDataAvailable = true;
          this.barChartLabels = [];
          this.barChartData = [];
          // Reset flag after fetching
          this.isFetchingData = false;
          // Keep default data in case of error
        }
      );
      
      // Add subscription to array for cleanup
      this.subscriptions.push(subscription);
    } else {
      console.log('Missing required data for bar chart:', { table: this.table, xAxis: this.xAxis, yAxis: this.yAxis, connection: this.connection });
      this.noDataAvailable = true;
      this.barChartLabels = [];
      this.barChartData = [];
      // Reset flag after fetching
      this.isFetchingData = 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.barChartLabels = [];
        this.barChartData = [];
        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.barChartLabels = [];
      this.barChartData = [];
      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);
    }
    
    // Log the URL that will be called
    let url = `chart/getdashjson/bar?tableName=${actualApiUrl}&xAxis=${drilldownConfig.xAxis}&yAxes=${drilldownConfig.yAxis}${this.connection ? `&sureId=${this.connection}` : ''}`;
    if (parameterField && parameterValue) {
      url += `&parameter=${encodeURIComponent(parameterField)}&parameterValue=${encodeURIComponent(parameterValue)}`;
    }
    console.log('Drilldown data URL:', url);
    
    // 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);
      }
    }
    console.log('Drilldown layer filter parameters:', filterParams);
    
    // Convert drilldownFilters to filter parameters for drilldown level
    let drilldownFilterParams = '';
    if (this.drilldownFilters && this.drilldownFilters.length > 0) {
      const filterObj = {};
      this.drilldownFilters.forEach(filter => {
        if (filter.field && filter.value) {
          filterObj[filter.field] = filter.value;
        }
      });
      if (Object.keys(filterObj).length > 0) {
        drilldownFilterParams = 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 (drilldownFilterParams) {
        try {
          const drilldownFilterObj = JSON.parse(drilldownFilterParams);
          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) {
        drilldownFilterParams = JSON.stringify(mergedFilterObj);
      }
    }
    
    console.log('Drilldown filter parameters:', drilldownFilterParams);
    
    // For drilldown level, we pass the parameter value from the drilldown stack and drilldown filters
    const subscription = this.dashboardService.getChartData(
      drilldownConfig.apiUrl, 'bar', 
      this.drilldownXAxis, this.drilldownYAxis, 
      this.connection, 
      '', parameterValue,
      drilldownFilterParams
    ).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.barChartLabels = [];
          this.barChartData = [];
          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.barChartLabels = data.chartLabels;
          this.barChartData = data.chartData;
          // Trigger change detection
          // this.barChartData = [...this.barChartData];
          console.log('Updated bar chart with drilldown data:', { labels: this.barChartLabels, data: this.barChartData });
        } else if (data && data.labels && data.datasets) {
          // Backend has already filtered the data, just display it
          this.noDataAvailable = data.labels.length === 0;
          this.barChartLabels = data.labels;
          this.barChartData = data.datasets;
          console.log('Updated bar chart with drilldown legacy data format:', { labels: this.barChartLabels, data: this.barChartData });
        } else {
          console.warn('Drilldown received data does not have expected structure', data);
          this.noDataAvailable = true;
          this.barChartLabels = [];
          this.barChartData = [];
        }
      },
      (error) => {
        console.error('Error fetching drilldown data:', error);
        this.noDataAvailable = true;
        this.barChartLabels = [];
        this.barChartData = [];
        // Keep current data in case of error
      }
    );
    
    // Add subscription to array for cleanup
    this.subscriptions.push(subscription);
  }
  
  // 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.originalBarChartLabels.length > 0) {
      // Create a deep copy to avoid reference issues
      this.barChartLabels = JSON.parse(JSON.stringify(this.originalBarChartLabels));
      console.log('Restored original labels');
    }
    if (this.originalBarChartData.length > 0) {
      // Create a deep copy to avoid reference issues
      this.barChartData = JSON.parse(JSON.stringify(this.originalBarChartData));
      console.log('Restored original data');
    }
    
    console.log('After reset - labels:', this.barChartLabels);
    console.log('After reset - data:', this.barChartData);
    
    // 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();
    }
  }

  // Public method to refresh data when filters change
  refreshData(): void {
    this.fetchChartData();
  }
  
  // Method to handle window resize events
  onResize(): void {
    if (this.chart) {
      this.chart.chart?.resize();
    }
  }
  
  // Ensure labels and data arrays have the same length
  private syncLabelAndDataArrays(): void {
    // For bar charts, we need to ensure all datasets have the same number of data points
    if (this.barChartData && this.barChartData.length > 0 && this.barChartLabels) {
      const labelCount = this.barChartLabels.length;
      
      this.barChartData.forEach(dataset => {
        if (dataset.data) {
          // If dataset has more data points than labels, truncate the data
          if (dataset.data.length > labelCount) {
            dataset.data = dataset.data.slice(0, labelCount);
          }
          // If dataset has fewer data points than labels, pad with zeros
          else if (dataset.data.length < labelCount) {
            while (dataset.data.length < labelCount) {
              dataset.data.push(0);
            }
          }
        }
      });
    }
  }

  // events
  public chartClicked(e: any): void {
    console.log('Bar 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.barChartLabels[clickedIndex];
      
      console.log('Clicked on bar:', { 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
        // Create a deep copy to avoid reference issues
        this.originalBarChartLabels = JSON.parse(JSON.stringify(this.barChartLabels));
        // Create a deep copy to avoid reference issues
        this.originalBarChartData = JSON.parse(JSON.stringify(this.barChartData));
        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(e);
  }
  
  ngOnDestroy() {
    // Unsubscribe from all subscriptions to prevent memory leaks
    console.log('BarChartComponent ngOnDestroy called, unsubscribing from', this.subscriptions.length, 'subscriptions');
    this.subscriptions.forEach(subscription => {
      if (subscription && !subscription.closed) {
        subscription.unsubscribe();
      }
    });
    this.subscriptions = [];
    
    // Clear data to help with garbage collection
    this.barChartLabels = [];
    this.barChartData = [];
    this.drilldownStack = [];
    this.originalBarChartLabels = [];
    this.originalBarChartData = [];
    
    console.log('BarChartComponent destroyed and cleaned up');
  }
}