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';

@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
  // Multi-layer drilldown configuration inputs
  @Input() drilldownLayers: any[] = []; // Array of drilldown layer configurations

  public bubbleChartOptions: ChartConfiguration['options'] = {
    // scales: {
    //   x: {
    //     min: 0,
    //     max: 30,
    //     ticks: {}
    //   },
    //   y: {
    //     min: 0,
    //     max: 30,
    //     ticks: {}
    //   },
    //   plugins: {
    //     title: {
    //       display: true,
    //       text: 'Bubble Chart'
    //     }
    //   }
    // }
  };

  public bubbleChartType: string = 'bubble';
  public bubbleChartData: ChartDataset[] = [
    {
      data: [
        { x: 10, y: 10, r: 10 },
        { x: 15, y: 5, r: 15 },
        { x: 26, y: 12, r: 23 },
        { x: 7, y: 8, r: 8 },
      ],
      label: 'Investment Equities',
      backgroundColor: 'rgba(255, 0, 0, 0.6)', // Red
      borderColor: 'blue',
      hoverBackgroundColor: 'purple',
      hoverBorderColor: 'red',
    },
    {
      data: [
        { x: 5, y: 15, r: 12 },
        { x: 20, y: 7, r: 8 },
        { x: 12, y: 18, r: 15 },
        { x: 8, y: 6, r: 10 },
      ],
      label: 'Investment Bonds',
      backgroundColor: 'rgba(0, 255, 0, 0.6)', // Green
      borderColor: 'green',
      hoverBackgroundColor: 'yellow',
      hoverBorderColor: 'blue',
    },
  ];
  
  // 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;

  constructor(private dashboardService: Dashboard3Service) { }

  ngOnInit(): void {
    this.fetchChartData();
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('BubbleChartComponent 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;
    // 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;
    
    // Respond to input changes
    if (xAxisChanged || yAxisChanged || tableChanged || connectionChanged || 
        drilldownEnabledChanged || drilldownApiUrlChanged || drilldownXAxisChanged || drilldownYAxisChanged ||
        drilldownLayersChanged) {
      console.log('X or Y axis or table or connection or drilldown config changed, fetching new data');
      this.fetchChartData();
    }
  }

  fetchChartData(): void {
    // If we're in drilldown mode, fetch the appropriate drilldown data
    if (this.currentDrilldownLevel > 0 && this.drilldownStack.length > 0) {
      this.fetchDrilldownData();
      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;
      
      // 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
      this.dashboardService.getChartData(this.table, 'bubble', this.xAxis, yAxisString, this.connection, '', '').subscribe(
        (data: any) => {
          console.log('Received bubble chart data:', data);
          if (data === null) {
            console.warn('Bubble chart API returned null data. Check if the API endpoint is working correctly.');
            this.noDataAvailable = true;
            this.bubbleChartData = [];
            return;
          }
          
          // Handle the actual data structure returned by the API
          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}
            this.noDataAvailable = data.chartLabels.length === 0;
            this.bubbleChartData = this.transformToBubbleData(data.chartLabels, data.chartData);
            console.log('Updated bubble chart with data:', this.bubbleChartData);
          } else if (data && data.labels && data.datasets) {
            // Handle the original expected format as fallback
            this.noDataAvailable = data.labels.length === 0;
            this.bubbleChartData = data.datasets;
            console.log('Updated bubble chart with legacy data format:', this.bubbleChartData);
          } else {
            console.warn('Bubble chart received data does not have expected structure', data);
            this.noDataAvailable = true;
            this.bubbleChartData = [];
          }
        },
        (error) => {
          console.error('Error fetching bubble chart data:', error);
          this.noDataAvailable = true;
          this.bubbleChartData = [];
        }
      );
    } 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 = [];
    }
  }
  
  // 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 = [];
        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 = [];
      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
    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).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.bubbleChartData = [];
          return;
        }
        
        // Handle the actual data structure returned by the API
        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}
          this.noDataAvailable = data.chartLabels.length === 0;
          this.bubbleChartData = this.transformToBubbleData(data.chartLabels, data.chartData);
          console.log('Updated bubble chart with drilldown data:', this.bubbleChartData);
        } else if (data && data.labels && data.datasets) {
          // Handle the original expected format as fallback
          this.noDataAvailable = data.labels.length === 0;
          this.bubbleChartData = data.datasets;
          console.log('Updated bubble chart with drilldown legacy data format:', this.bubbleChartData);
        } else {
          console.warn('Drilldown received data does not have expected structure', data);
          this.noDataAvailable = true;
          this.bubbleChartData = [];
        }
      },
      (error) => {
        console.error('Error fetching drilldown data:', error);
        this.noDataAvailable = true;
        this.bubbleChartData = [];
      }
    );
  }
  
  // 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();
    }
  }

  private transformToBubbleData(labels: any[], chartData: any[]): ChartDataset[] {
    // Transform the API data into bubble chart format
    const datasets: ChartDataset[] = [];
    
    // Create a dataset for each data series
    chartData.forEach((series, index) => {
      // For bubble charts, we need x, y, and r values
      // We'll use the labels as x values and the data as y values
      // For radius (r), we'll use a default value or derive it from the data
      
      const bubbleData = labels.map((label, i) => {
        const xValue = isNaN(Number(label)) ? i : Number(label);
        const yValue = series.data && series.data[i] !== undefined ? 
          (isNaN(Number(series.data[i])) ? 0 : Number(series.data[i])) : 0;
        // Use a default radius or derive from data
        const radius = Math.abs(yValue) > 0 ? Math.abs(yValue) / 10 : 5;
        
        return {
          x: xValue,
          y: yValue,
          r: radius
        };
      });
      
      datasets.push({
        data: bubbleData,
        label: series.label || `Series ${index + 1}`,
        backgroundColor: this.getBackgroundColor(index),
        borderColor: this.getBorderColor(index),
        hoverBackgroundColor: this.getHoverBackgroundColor(index),
        hoverBorderColor: this.getHoverBorderColor(index),
      });
    });
    
    return datasets;
  }

  private getBackgroundColor(index: number): string {
    const colors = [
      'rgba(255, 0, 0, 0.6)',    // Red
      'rgba(0, 255, 0, 0.6)',    // Green
      'rgba(0, 0, 255, 0.6)',    // Blue
      'rgba(255, 255, 0, 0.6)',  // Yellow
      'rgba(255, 0, 255, 0.6)',  // Magenta
      'rgba(0, 255, 255, 0.6)',  // Cyan
    ];
    return colors[index % colors.length];
  }

  private getBorderColor(index: number): string {
    const colors = ['blue', 'green', 'red', 'orange', 'purple', 'cyan'];
    return colors[index % colors.length];
  }

  private getHoverBackgroundColor(index: number): string {
    const colors = ['purple', 'yellow', 'orange', 'red', 'blue', 'green'];
    return colors[index % colors.length];
  }

  private getHoverBorderColor(index: number): string {
    const colors = ['red', 'blue', 'green', 'purple', 'yellow', 'orange'];
    return colors[index % colors.length];
  }

  // 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: datasetIndex, index: clickedIndex, dataPoint: 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) {
        // For bubble charts, we'll use the x value as the clicked value
        const clickedValue = dataPoint && (dataPoint as any).x !== undefined ? 
          (dataPoint as any).x.toString() : '';
        
        // Add this click to the drilldown stack
        const stackEntry = {
          level: nextDrilldownLevel,
          datasetIndex: datasetIndex,
          clickedIndex: clickedIndex,
          clickedValue: clickedValue
        };
        
        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);
  }
}