import { Component, OnInit, ViewChild, AfterViewInit, 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-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;
  
  private filterSubscription: Subscription = new Subscription();
  
  // Loading state
  isLoading: boolean = false;

  public barChartOptions: ChartConfiguration['options'] = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        grid: {
          color: 'rgba(0, 0, 0, 0.05)'
        },
        ticks: {
          color: '#64748b'
        }
      },
      y: {
        beginAtZero: true,
        grid: {
          color: 'rgba(0, 0, 0, 0.05)'
        },
        ticks: {
          color: '#64748b'
        }
      }
    },
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        backgroundColor: 'rgba(10, 25, 47, 0.9)',
        titleColor: '#ff6b35',
        bodyColor: '#ffffff',
        borderColor: 'rgba(255, 107, 53, 0.3)',
        borderWidth: 1,
        cornerRadius: 6
      }
    }
  };

  public barChartType: ChartType = 'bar';
  public barChartPlugins = [];

  public barChartData: ChartData<'bar'> = {
    labels: ['Prospecting', 'Qualification', 'Needs Analysis', 'Value Proposition', 'Decision Making', 'Negotiation'],
    datasets: [
      {
        data: [65, 59, 80, 81, 56, 55],
        label: 'Deal Progress',
        backgroundColor: '#0a192f',
        borderColor: '#0a192f',
        borderWidth: 1,
        borderRadius: 4
      }
    ]
  };

  constructor(private filterService: DashboardFilterService) { }

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

  ngAfterViewInit(): void {
    // Initial chart render
    this.updateChart();
  }
  
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this.filterSubscription.unsubscribe();
  }

  // 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
    const baseData = [65, 59, 80, 81, 56, 55];
    
    // 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;
    
    // Add a small delay to simulate loading
    setTimeout(() => {
      this.barChartData.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);
  }
}