import { Component, OnInit, OnDestroy } from '@angular/core';
import { DashboardFilterService } from '../../services/dashboard-filter.service';
import { Subscription } from 'rxjs';

interface CrossSellingItem {
  id: number;
  companyName: string;
  contactPerson: string;
  product: string;
  potentialValue: number;
  probability: number;
  nextAction: string;
  actionDate: string;
}

@Component({
  selector: 'app-shield-data-table',
  templateUrl: './data-table.component.html',
  styleUrls: ['./data-table.component.scss']
})
export class DataTableComponent implements OnInit, OnDestroy {
  private filterSubscription: Subscription = new Subscription();
  
  // Mock data for cross/up selling scope
  originalCrossSellingData: CrossSellingItem[] = [
    { id: 1, companyName: 'Tech Solutions Inc', contactPerson: 'John Smith', product: 'Product A', potentialValue: 50000, probability: 75, nextAction: 'Follow-up call', actionDate: '2023-06-15' },
    { id: 2, companyName: 'Global Enterprises', contactPerson: 'Sarah Johnson', product: 'Product B', potentialValue: 75000, probability: 60, nextAction: 'Send proposal', actionDate: '2023-06-18' },
    { id: 3, companyName: 'Innovative Systems', contactPerson: 'Mike Brown', product: 'Product C', potentialValue: 30000, probability: 85, nextAction: 'Demo scheduled', actionDate: '2023-06-20' },
    { id: 4, companyName: 'Future Tech Ltd', contactPerson: 'Emily Davis', product: 'Product A', potentialValue: 45000, probability: 70, nextAction: 'Send quote', actionDate: '2023-06-22' },
    { id: 5, companyName: 'Digital Dynamics', contactPerson: 'Robert Wilson', product: 'Product B', potentialValue: 60000, probability: 55, nextAction: 'Meeting scheduled', actionDate: '2023-06-25' },
    { id: 6, companyName: 'Alpha Solutions', contactPerson: 'Lisa Miller', product: 'Product C', potentialValue: 40000, probability: 80, nextAction: 'Follow-up email', actionDate: '2023-06-28' },
    { id: 7, companyName: 'Beta Innovations', contactPerson: 'David Taylor', product: 'Product A', potentialValue: 55000, probability: 65, nextAction: 'Product demo', actionDate: '2023-06-28' },
    { id: 8, companyName: 'Gamma Technologies', contactPerson: 'Jennifer Anderson', product: 'Product B', potentialValue: 70000, probability: 50, nextAction: 'Proposal review', actionDate: '2023-07-05' }
  ];
  
  crossSellingData: CrossSellingItem[] = [...this.originalCrossSellingData];

  // Sorting properties
  sortColumn: keyof CrossSellingItem = 'companyName';
  sortDirection: 'asc' | 'desc' = 'asc';

  constructor(private filterService: DashboardFilterService) { }

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

  // Update table data based on filters
  updateTableData(filters: any): void {
    // Simulate data change based on filters
    // In a real implementation, this would fetch new data from an API
    
    if (filters.salesRep || filters.partner || filters.tractionChannel || filters.subProductLine) {
      // Apply filter effects (simplified logic)
      const filteredData = this.originalCrossSellingData.filter(item => {
        // Simple filtering logic - in a real app, this would be more sophisticated
        return Math.random() > 0.3; // Randomly filter out some items
      });
      
      this.crossSellingData = filteredData;
    } else {
      // No filters applied, show all data
      this.crossSellingData = [...this.originalCrossSellingData];
    }
    
    // Re-apply current sorting
    this.sortTable(this.sortColumn);
  }

  // Sort table by column
  sortTable(column: keyof CrossSellingItem): void {
    if (this.sortColumn === column) {
      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortColumn = column;
      this.sortDirection = 'asc';
    }

    this.crossSellingData.sort((a, b) => {
      const aValue = a[column];
      const bValue = b[column];

      if (aValue < bValue) {
        return this.sortDirection === 'asc' ? -1 : 1;
      }
      if (aValue > bValue) {
        return this.sortDirection === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }

  // Format currency
  formatCurrency(value: number): string {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(value);
  }

  // Format probability as percentage
  formatProbability(probability: number): string {
    return `${probability}%`;
  }
}