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

@Component({
  selector: 'app-bubble-chart',
  templateUrl: './bubble-chart.component.html',
  styleUrls: ['./bubble-chart.component.scss']
})
export class BubbleChartComponent implements OnInit, OnChanges {
  @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 bubbleChartOptions: ChartConfiguration['options'] = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        beginAtZero: true,
        title: {
          display: true,
          text: 'X Axis'
        },
        ticks: {
          autoSkip: false,
          maxRotation: 45,
          minRotation: 45
        }
      },
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: 'Y Axis'
        }
      }
    },
    plugins: {
      legend: {
        display: true,
        position: 'top',
      },
      tooltip: {
        enabled: true,
        mode: 'point',
        intersect: false,
        callbacks: {
          label: function(context: any) {
            const point: any = context.raw;
            if (point && point.hasOwnProperty('y') && point.hasOwnProperty('r')) {
              const yValue = parseFloat(point.y);
              const rValue = parseFloat(point.r);
              if (!isNaN(yValue) && !isNaN(rValue)) {
                return `Value: ${yValue.toFixed(2)}, Size: ${rValue.toFixed(1)}`;
              }
            }
            return context.dataset.label || '';
          }
        }
      }
    },
    animation: {
      duration: 800,
      easing: 'easeInOutQuart'
    },
    // Enable individual point styling
    elements: {
      point: {
        hoverRadius: 12,
        hoverBorderWidth: 3
      }
    },
    // Add padding to ensure x-axis labels are visible
    layout: {
      padding: {
        left: 10,
        right: 10,
        top: 10,
        bottom: 30
      }
    }
  };

  public bubbleChartType: string = 'bubble';
  public bubbleChartData: ChartDataset[] = [];
  
  // Multi-layer drilldown state tracking
  drilldownStack: any[] = []; // Stack to track drilldown navigation history
  currentDrilldownLevel: number = 0; // Current drilldown level (0 = base level)
  originalBubbleChartData: ChartDataset[] = [];
  
  // No data state
  noDataAvailable: boolean = false;
  dataLoaded: boolean = false; // Track if data has been loaded
  
  // 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();
      })
    );
    
    this.fetchChartData();
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('BubbleChartComponent 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();
    }
  }
  
  // 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();
  }
  
  // Helper function to replace alpha value in RGBA color string
  private replaceAlpha(color: string, newAlpha: number): string {
    // Match rgba(r, g, b, a) format and replace alpha value
    return color.replace(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d.]+\)/, `rgba($1, $2, $3, ${newAlpha})`);
  }
  
  // Function to generate different colors for bubbles
  private generateBubbleColor(index: number, value: number, total: number): string {
    // Generate colors based on index or value
    // Using HSL color model for better color distribution
    const hue = (index * 137.508) % 360; // Golden angle approximation for good distribution
    const saturation = 80 + (index % 20); // High saturation for vibrant colors
    const lightness = 40 + (index % 30); // Vary lightness for contrast
    
    // Convert HSL to RGB
    const h = hue / 360;
    const s = saturation / 100;
    const l = lightness / 100;
    
    const rgb = this.hslToRgb(h, s, l);
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.7)`;
  }
  
  // Helper function to convert HSL to RGB
  private hslToRgb(h: number, s: number, l: number): { r: number, g: number, b: number } {
    let r, g, b;
    
    if (s === 0) {
      r = g = b = l; // achromatic
    } else {
      const hue2rgb = (p: number, q: number, t: number) => {
        if (t < 0) t += 1;
        if (t > 1) t -= 1;
        if (t < 1/6) return p + (q - p) * 6 * t;
        if (t < 1/2) return q;
        if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
      };
      
      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r = hue2rgb(p, q, h + 1/3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1/3);
    }
    
    return {
      r: Math.round(r * 255),
      g: Math.round(g * 255),
      b: Math.round(b * 255)
    };
  }
  
  // Helper function to calculate logarithmic scaling
  private logScale(value: number, min: number, max: number, minRadius: number, maxRadius: number): number {
    if (min === max) return (minRadius + maxRadius) / 2;
    
    // Normalize value to 0-1 range
    const normalized = (value - min) / (max - min);
    
    // Apply logarithmic scaling (base 10)
    // Add 1 to avoid log(0) and scale to 1-10 range
    const logValue = Math.log10(normalized * 9 + 1);
    
    // Scale to desired radius range
    return minRadius + (logValue / Math.log10(10)) * (maxRadius - minRadius);
  }
  
  // Transform data to bubble chart format
  private transformToBubbleData(labels: any[], data: any[]): ChartDataset[] {
    // For bubble charts, we need to transform the data into bubble format
    // Bubble charts expect data in the format: {x: number, y: number, r: number}
    console.log('Transforming data to bubble format:', { labels, data });
    
    // Handle null/undefined data
    if (!labels || !data) {
      console.log('Labels or data is null/undefined, returning empty dataset');
      return [];
    }
    
    // If we have the expected bubble data format, return it as is
    if (data && data.length > 0 && data[0].data && data[0].data.length > 0 && 
        typeof data[0].data[0] === 'object' && data[0].data[0].hasOwnProperty('x') && 
        data[0].data[0].hasOwnProperty('y') && data[0].data[0].hasOwnProperty('r')) {
      console.log('Data is already in bubble format, returning as is');
      return data;
    }
    
    // Transform the data properly for bubble chart
    // Assuming labels are x-values and data[0].data are y-values
    if (labels && data && data.length > 0 && data[0].data) {
      console.log('Transforming regular data to bubble format');
      const yValues = data[0].data;
      const label = data[0].label || 'Dataset 1';
      
      // Handle case where yValues might not be an array
      if (!Array.isArray(yValues)) {
        console.log('yValues is not an array, returning empty dataset');
        return [];
      }
      
      console.log('yValues type:', typeof yValues);
      console.log('yValues length:', yValues.length);
      console.log('First few yValues:', yValues.slice(0, 5));
      
      // Find min and max values for scaling
      let minValue = Infinity;
      let maxValue = -Infinity;
      const validYValues = [];
      
      // First pass: collect valid values and find min/max
      for (let i = 0; i < yValues.length; i++) {
        let y;
        if (typeof yValues[i] === 'string') {
          y = parseFloat(yValues[i]);
        } else {
          y = yValues[i];
        }
        
        if (!isNaN(y)) {
          validYValues.push(y);
          minValue = Math.min(minValue, y);
          maxValue = Math.max(maxValue, y);
        }
      }
      
      console.log('Value range:', { minValue, maxValue });
      
      // Adjust radius range based on number of data points
      // For fewer points, we can use larger bubbles; for more points, smaller bubbles to prevent overlap
      const dataPointCount = Math.min(labels.length, yValues.length);
      let minRadius = 3;
      let maxRadius = 30;
      
      // Adjust radius range based on data point count
      if (dataPointCount > 50) {
        minRadius = 2;
        maxRadius = 20;
      } else if (dataPointCount > 20) {
        minRadius = 3;
        maxRadius = 25;
      }
      
      console.log('Radius range:', { minRadius, maxRadius, dataPointCount });
      
      // Create bubble points from labels (x) and data (y)
      const bubblePoints = [];
      const bubbleColors = [];
      const minLength = Math.min(labels.length, yValues.length);
      
      console.log('Processing data points:', { labels, yValues, minLength });
      
      for (let i = 0; i < minLength; i++) {
        // Log each point for debugging
        console.log(`Processing point ${i}: label=${labels[i]}, yValue=${yValues[i]}, type=${typeof yValues[i]}`);
        
        // Convert y to number if it's a string
        let y;
        if (typeof yValues[i] === 'string') {
          y = parseFloat(yValues[i]);
          console.log(`Converted string yValue to number: ${yValues[i]} -> ${y}`);
        } else {
          y = yValues[i];
        }
        
        // Handle NaN values
        if (isNaN(y)) {
          console.log(`Skipping point ${i} due to NaN y value: ${yValues[i]}`);
          continue;
        }
        
        // Calculate radius based on the y-value with logarithmic scaling
        const r = this.logScale(y, minValue, maxValue, minRadius, maxRadius);
        
        console.log(`Value: ${y}, Radius: ${r}`);
        
        // For x-value, we'll use the index position since labels are strings
        const x = i;
        
        // Generate a unique color for this bubble
        const backgroundColor = this.generateBubbleColor(i, y, minLength);
        
        // Store the color for the dataset
        bubbleColors.push(backgroundColor);
        
        // Add the point
        const point = { 
          x, 
          y, 
          r
        };
        console.log(`Adding point ${i}:`, point);
        bubblePoints.push(point);
      }
      
      console.log('Generated bubble points:', bubblePoints);
      console.log('Generated bubble points count:', bubblePoints.length);
      console.log('Generated bubble colors count:', bubbleColors.length);
      
      // If we have no valid points, return empty array
      if (bubblePoints.length === 0) {
        console.log('No valid bubble points generated, returning empty dataset');
        return [];
      }
      
      // Create a single dataset with all bubble points
      const bubbleDatasets: ChartDataset[] = [
        {
          data: bubblePoints,
          label: label,
          backgroundColor: bubbleColors,
          borderColor: bubbleColors.map(color => this.replaceAlpha(color, 1)), // Slightly more opaque border
          hoverBackgroundColor: bubbleColors.map(color => this.replaceAlpha(color, 0.9)),
          hoverBorderColor: 'rgba(255, 255, 255, 1)',
          borderWidth: 2,
          pointHoverRadius: 10,
        }
      ];
      
      console.log('Transformed bubble data:', bubbleDatasets);
      return bubbleDatasets;
    }
    
    console.log('Could not transform data, returning empty dataset');
    // Return empty dataset instead of default data
    return [];
  }

  fetchChartData(): void {
    // Set flag to prevent recursive calls
    this.isFetchingData = true;
    this.dataLoaded = false; // Mark data as not loaded yet
    this.noDataAvailable = false; // Reset no data flag
    
    console.log('Starting fetchChartData, current state:', {
      table: this.table,
      xAxis: this.xAxis,
      yAxis: this.yAxis,
      connection: this.connection
    });
    
    // If we're in drilldown mode, fetch the appropriate drilldown data
    if (this.currentDrilldownLevel > 0 && this.drilldownStack.length > 0) {
      console.log('Fetching drilldown data');
      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('Fetching bubble 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/bubble?tableName=${this.table}&xAxis=${this.xAxis}&yAxes=${yAxisString}${this.connection ? `&sureId=${this.connection}` : ''}`;
      console.log('Bubble 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, 'bubble', this.xAxis, yAxisString, this.connection, '', '', filterParams).subscribe(
        (data: any) => {
          console.log('Received bubble chart data:', data);
          
          // Reset chart data to empty first
          this.bubbleChartData = [];
          
          if (data === null || data === undefined) {
            console.warn('Bubble chart API returned null/undefined data. Check if the API endpoint is working correctly.');
            this.noDataAvailable = true;
          } else if (data && data.chartLabels && data.chartData) {
            // For bubble charts, we need to transform the data into bubble format
            // Bubble charts expect data in the format: {x: number, y: number, r: number}
            console.log('Processing chartLabels and chartData format');
            const transformedData = this.transformToBubbleData(data.chartLabels, data.chartData);
            console.log('Transformed data:', transformedData);
            
            // Check if we have valid data
            let hasValidData = false;
            if (transformedData && transformedData.length > 0) {
              for (const dataset of transformedData) {
                if (dataset.data && dataset.data.length > 0) {
                  hasValidData = true;
                  break;
                }
              }
            }
            
            if (hasValidData) {
              // Create a new array reference to trigger change detection
              this.bubbleChartData = [...transformedData];
              this.noDataAvailable = false;
              console.log('Updated bubble chart with data:', this.bubbleChartData);
            } else {
              console.log('No valid data after transformation');
              this.noDataAvailable = true;
            }
          } else if (data && data.labels && data.datasets) {
            // Handle the original expected format as fallback
            console.log('Processing labels and datasets format');
            // Check if we have valid data
            let hasValidData = false;
            if (data.datasets && data.datasets.length > 0) {
              for (const dataset of data.datasets) {
                if (dataset.data && dataset.data.length > 0) {
                  hasValidData = true;
                  break;
                }
              }
            }
            
            if (hasValidData) {
              // Create a new array reference to trigger change detection
              this.bubbleChartData = [...data.datasets];
              this.noDataAvailable = false;
              console.log('Updated bubble chart with legacy data format:', this.bubbleChartData);
            } else {
              console.log('No valid data in legacy format');
              this.noDataAvailable = true;
            }
          } else {
            console.warn('Bubble chart received data does not have expected structure', data);
            this.noDataAvailable = true;
          }
          
          this.dataLoaded = true; // Mark data as loaded
          
          console.log('Final state after data fetch:', {
            noDataAvailable: this.noDataAvailable,
            dataLoaded: this.dataLoaded,
            bubbleChartDataLength: this.bubbleChartData.length,
            isChartDataValid: this.isChartDataValid()
          });
          
          // Trigger change detection with a small delay to ensure proper rendering
          setTimeout(() => {
            this.forceChartUpdate();
          }, 100);
          
          // Reset flag after fetching
          this.isFetchingData = false;
        },
        (error) => {
          console.error('Error fetching bubble chart data:', error);
          this.noDataAvailable = true;
          this.bubbleChartData = [];
          this.dataLoaded = true;
          // Trigger change detection
          setTimeout(() => {
            this.forceChartUpdate();
          }, 100);
          // Reset flag after fetching
          this.isFetchingData = false;
        }
      );
    } else {
      console.log('Missing required data for bubble chart:', { table: this.table, xAxis: this.xAxis, yAxis: this.yAxis, connection: this.connection });
      this.noDataAvailable = true;
      this.bubbleChartData = [];
      this.dataLoaded = true;
      // Trigger change detection
      setTimeout(() => {
        this.forceChartUpdate();
      }, 100);
      // 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.bubbleChartData = [];
        this.dataLoaded = true;
        setTimeout(() => {
          this.forceChartUpdate();
        }, 100);
        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.bubbleChartData = [];
      this.dataLoaded = true;
      setTimeout(() => {
        this.forceChartUpdate();
      }, 100);
      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/bubble?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, 'bubble', drilldownConfig.xAxis, drilldownConfig.yAxis, this.connection, parameterField, parameterValue, filterParams).subscribe(
      (data: any) => {
        console.log('Received drilldown data:', data);
        
        // Reset chart data to empty first
        this.bubbleChartData = [];
        
        if (data === null || data === undefined) {
          console.warn('Drilldown API returned null/undefined data. Check if the API endpoint is working correctly.');
          this.noDataAvailable = true;
        } else if (data && data.chartLabels && data.chartData) {
          // For bubble charts, we need to transform the data into bubble format
          const transformedData = this.transformToBubbleData(data.chartLabels, data.chartData);
          
          // Check if we have valid data
          let hasValidData = false;
          if (transformedData && transformedData.length > 0) {
            for (const dataset of transformedData) {
              if (dataset.data && dataset.data.length > 0) {
                hasValidData = true;
                break;
              }
            }
          }
          
          if (hasValidData) {
            this.bubbleChartData = transformedData;
            this.noDataAvailable = false;
            console.log('Updated bubble chart with drilldown data:', this.bubbleChartData);
          } else {
            console.log('No valid data after transformation in drilldown');
            this.noDataAvailable = true;
          }
        } else if (data && data.labels && data.datasets) {
          // Handle the original expected format as fallback
          // Check if we have valid data
          let hasValidData = false;
          if (data.datasets && data.datasets.length > 0) {
            for (const dataset of data.datasets) {
              if (dataset.data && dataset.data.length > 0) {
                hasValidData = true;
                break;
              }
            }
          }
          
          if (hasValidData) {
            this.bubbleChartData = data.datasets;
            this.noDataAvailable = false;
            console.log('Updated bubble chart with drilldown legacy data format:', this.bubbleChartData);
          } else {
            console.log('No valid data in legacy format in drilldown');
            this.noDataAvailable = true;
          }
        } else {
          console.warn('Drilldown received data does not have expected structure', data);
          this.noDataAvailable = true;
        }
        
        this.dataLoaded = true; // Mark data as loaded
        
        console.log('Final state after drilldown data fetch:', {
          noDataAvailable: this.noDataAvailable,
          dataLoaded: this.dataLoaded,
          bubbleChartDataLength: this.bubbleChartData.length,
          isChartDataValid: this.isChartDataValid()
        });
        
        // Trigger change detection
        setTimeout(() => {
          this.forceChartUpdate();
        }, 100);
      },
      (error) => {
        console.error('Error fetching drilldown data:', error);
        this.noDataAvailable = true;
        this.bubbleChartData = [];
        this.dataLoaded = true;
        setTimeout(() => {
          this.forceChartUpdate();
        }, 100);
      }
    );
  }
  
  // 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.originalBubbleChartData.length > 0) {
      this.bubbleChartData = [...this.originalBubbleChartData];
      console.log('Restored original data');
    }
    
    console.log('After reset - data:', this.bubbleChartData);
    
    // 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();
    }
  }

  // events
  public chartClicked(e: any): void {
    console.log('Bubble 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 dataset index
      const datasetIndex = e.active[0].datasetIndex;
      
      // Get the data point
      const dataPoint = this.bubbleChartData[datasetIndex].data[clickedIndex];
      
      console.log('Clicked on bubble:', { datasetIndex, clickedIndex, dataPoint });
      
      // If we're not at the base level, store original data
      if (this.currentDrilldownLevel === 0) {
        // Store original data before entering drilldown mode
        this.originalBubbleChartData = JSON.parse(JSON.stringify(this.bubbleChartData));
        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,
          datasetIndex: datasetIndex,
          clickedIndex: clickedIndex,
          dataPoint: dataPoint,
          clickedValue: dataPoint // Using data point 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('Bubble chart hovered:', e);
  }

  // Method to check if chart data is valid
  public isChartDataValid(): boolean {
    console.log('Checking if chart data is valid:', this.bubbleChartData);
    if (!this.bubbleChartData || this.bubbleChartData.length === 0) {
      console.log('Chart data is null or empty');
      return false;
    }
    
    // Check if any dataset has data
    for (const dataset of this.bubbleChartData) {
      console.log('Checking dataset:', dataset);
      if (dataset.data && dataset.data.length > 0) {
        console.log('Dataset has data, length:', dataset.data.length);
        // For bubble charts, check if data points have x, y, r properties
        for (const point of dataset.data) {
          console.log('Checking point:', point);
          if (typeof point === 'object' && point.hasOwnProperty('x') && point.hasOwnProperty('y') && point.hasOwnProperty('r')) {
            // Valid bubble point
            console.log('Found valid bubble point');
            return true;
          }
        }
      }
    }
    
    console.log('No valid chart data found');
    return false;
  }

  // Method to force chart update
  private forceChartUpdate(): void {
    console.log('Forcing chart update');
    console.log('Current bubbleChartData:', this.bubbleChartData);
    console.log('Current bubbleChartData length:', this.bubbleChartData ? this.bubbleChartData.length : 0);
    if (this.bubbleChartData && this.bubbleChartData.length > 0) {
      console.log('First dataset data length:', this.bubbleChartData[0].data ? this.bubbleChartData[0].data.length : 0);
    }
    // Create a new reference to trigger change detection
    if (this.bubbleChartData) {
      this.bubbleChartData = [...this.bubbleChartData];
    }
    // Also update noDataAvailable to trigger UI changes
    this.noDataAvailable = this.noDataAvailable;
    console.log('Chart update forced, noDataAvailable:', this.noDataAvailable);
    console.log('Chart update forced, bubbleChartData length:', this.bubbleChartData ? this.bubbleChartData.length : 0);
    console.log('Chart update forced, isChartDataValid:', this.isChartDataValid());
  }
}