import { Component, Input, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts';
import { ChartConfiguration, ChartData, ChartEvent, ChartType } from 'chart.js';
import { DashboardFilterService } from '../../services/dashboard-filter.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-shield-donut-chart',
  templateUrl: './donut-chart.component.html',
  styleUrls: ['./donut-chart.component.scss']
})
export class DonutChartComponent implements OnInit, OnDestroy {
  @Input() chartType: 'endCustomer' | 'segmentPenetration' = 'endCustomer';
  
  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;
  
  private filterSubscription: Subscription = new Subscription();
  
  // Loading state
  isLoading: boolean = false;

  public donutChartOptions: ChartConfiguration['options'] = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: true,
        position: 'bottom',
        labels: {
          color: '#64748b',
          font: {
            size: 12
          },
          padding: 20
        }
      },
      tooltip: {
        backgroundColor: 'rgba(10, 25, 47, 0.9)',
        titleColor: '#ff6b35',
        bodyColor: '#ffffff',
        borderColor: 'rgba(255, 107, 53, 0.3)',
        borderWidth: 1,
        cornerRadius: 6,
        callbacks: {
          label: function(context) {
            const label = context.label || '';
            const value = context.parsed;
            return `${label}: ${value}`;
          }
        }
      }
    }
  };

  public donutChartType: ChartType = 'doughnut';
  public donutChartPlugins = [];

  // Data for End Customer Stage Split
  public endCustomerData: ChartData<'doughnut'> = {
    labels: ['Prospecting', 'Qualification', 'Needs Analysis', 'Value Proposition', 'Decision Making'],
    datasets: [
      {
        data: [30, 25, 20, 15, 10],
        backgroundColor: [
          '#0a192f',
          '#1e3a8a',
          '#3b82f6',
          '#60a5fa',
          '#93c5fd'
        ],
        hoverBackgroundColor: [
          '#1e3a8a',
          '#3b82f6',
          '#60a5fa',
          '#93c5fd',
          '#bfdbfe'
        ],
        borderWidth: 0
      }
    ]
  };

  // Data for Segment Penetration
  public segmentPenetrationData: ChartData<'doughnut'> = {
    labels: ['Enterprise', 'Mid-Market', 'SMB', 'Startup'],
    datasets: [
      {
        data: [40, 30, 20, 10],
        backgroundColor: [
          '#ff6b35',
          '#ff8c66',
          '#ffb099',
          '#ffd6cc'
        ],
        hoverBackgroundColor: [
          '#ff8c66',
          '#ffb099',
          '#ffd6cc',
          '#ffffff'
        ],
        borderWidth: 0
      }
    ]
  };

  constructor(private filterService: DashboardFilterService) { }

  ngOnInit(): void {
    // Subscribe to filter changes
    this.filterSubscription.add(
      this.filterService.filterState$.subscribe(filters => {
        this.updateChartData(filters);
      })
    );
  }
  
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this.filterSubscription.unsubscribe();
  }

  // Get chart data based on chart type
  get chartData(): ChartData<'doughnut'> {
    return this.chartType === 'endCustomer' ? this.endCustomerData : this.segmentPenetrationData;
  }

  // Get chart title based on chart type
  get chartTitle(): string {
    return this.chartType === 'endCustomer' 
      ? 'End Customer Stage Split' 
      : 'Segment Penetration';
  }

  // Update chart data based on filters
  updateChartData(filters: any): void {
    // Show loading state
    this.isLoading = true;
    
    // Simulate data change based on filters
    // In a real implementation, this would fetch new data from an API
    
    // Add a small delay to simulate loading
    setTimeout(() => {
      if (this.chartType === 'endCustomer') {
        const baseData = [30, 25, 20, 15, 10];
        
        // Apply filter effects (simplified logic)
        let multiplier = 1;
        if (filters.salesRep) multiplier *= 0.9;
        if (filters.partner) multiplier *= 0.85;
        if (filters.tractionChannel) multiplier *= 0.95;
        if (filters.subProductLine) multiplier *= 0.8;
        
        this.endCustomerData.datasets[0].data = baseData.map(value => 
          Math.floor(value * multiplier)
        );
      } else {
        const baseData = [40, 30, 20, 10];
        
        // Apply filter effects (simplified logic)
        let multiplier = 1;
        if (filters.salesRep) multiplier *= 0.85;
        if (filters.partner) multiplier *= 0.9;
        if (filters.tractionChannel) multiplier *= 0.95;
        if (filters.subProductLine) multiplier *= 0.75;
        
        this.segmentPenetrationData.datasets[0].data = baseData.map(value => 
          Math.floor(value * multiplier)
        );
      }
      
      // Update chart
      this.updateChart();
      
      // Hide loading state
      this.isLoading = false;
    }, 300);
  }

  // Update chart with new data
  updateChart(): void {
    if (this.chart) {
      this.chart.update();
    }
  }

  // events
  public chartClicked({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
    console.log(event, active);
  }

  public chartHovered({ event, active }: { event?: ChartEvent, active?: {}[] }): void {
    console.log(event, active);
  }
}