import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

// Define the filter state interface
export interface FilterState {
  salesRep: string;
  partner: string;
  tractionChannel: string;
  subProductLine: string;
}

@Injectable({
  providedIn: 'root'
})
export class DashboardFilterService {
  // Shared filter state using BehaviorSubject
  private filterStateSubject = new BehaviorSubject<FilterState>({
    salesRep: '',
    partner: '',
    tractionChannel: '',
    subProductLine: ''
  });
  
  public filterState$ = this.filterStateSubject.asObservable();
  
  // KPI data
  private kpiDataSubject = new BehaviorSubject<{ totalLeads: number; totalDeals: number }>({
    totalLeads: 1248,
    totalDeals: 842
  });
  
  public kpiData$ = this.kpiDataSubject.asObservable();

  constructor() { }
  
  // Update filter state
  updateFilter(filterType: keyof FilterState, value: string): void {
    const currentState = this.filterStateSubject.value;
    const newState = { ...currentState, [filterType]: value };
    this.filterStateSubject.next(newState);
    
    // Simulate KPI data change based on filters
    this.updateKpiData(newState);
  }
  
  // Reset all filters to default values
  resetFilters(): void {
    this.filterStateSubject.next({
      salesRep: '',
      partner: '',
      tractionChannel: '',
      subProductLine: ''
    });
    
    // Reset KPI data to default values
    this.kpiDataSubject.next({
      totalLeads: 1248,
      totalDeals: 842
    });
  }
  
  // Update KPI data based on filters (simulated)
  private updateKpiData(filters: FilterState): void {
    // This is a simplified simulation - in a real app, this would come from an API
    let totalLeads = 1248;
    let totalDeals = 842;
    
    // Apply filter effects (simplified logic)
    if (filters.salesRep) totalLeads = Math.floor(totalLeads * 0.8);
    if (filters.partner) totalDeals = Math.floor(totalDeals * 0.9);
    if (filters.tractionChannel) totalLeads = Math.floor(totalLeads * 0.85);
    if (filters.subProductLine) totalDeals = Math.floor(totalDeals * 0.95);
    
    this.kpiDataSubject.next({
      totalLeads,
      totalDeals
    });
  }
  
  // Get current filter values
  getCurrentFilters(): FilterState {
    return this.filterStateSubject.value;
  }
}