import { Component, OnInit } from '@angular/core';
import { GridsterConfig, GridsterItem } from 'angular-gridster2';

interface ShieldDashboardItem extends GridsterItem {
  chartType: string;
  name: string;
  id: number;
  component?: any;
}

@Component({
  selector: 'app-shield-dashboard',
  templateUrl: './shield-dashboard.component.html',
  styleUrls: ['./shield-dashboard.component.scss']
})
export class ShieldDashboardComponent implements OnInit {
  options: GridsterConfig;
  dashboard: Array<ShieldDashboardItem>;
  
  // Keep track of deleted items
  deletedItems: Array<ShieldDashboardItem> = [];

  constructor() { }

  ngOnInit(): void {
    this.options = {
      gridType: 'fit',
      enableEmptyCellDrop: true,
      emptyCellDropCallback: this.onDrop,
      pushItems: true,
      swap: true,
      pushDirections: { north: true, east: true, south: true, west: true },
      resizable: { enabled: true },
      itemChangeCallback: this.itemChange.bind(this),
      draggable: {
        enabled: true,
        ignoreContent: true,
        dropOverItems: true,
        dragHandleClass: 'drag-handler',
        ignoreContentClass: 'no-drag',
      },
      displayGrid: 'always',
      minCols: 10,
      minRows: 10,
      itemResizeCallback: this.itemResize.bind(this)
    };

    // Initialize the dashboard with empty canvas
    this.dashboard = [];
  }

  onDrop = (event: any) => {
    // Handle dropping new components onto the dashboard
    console.log('Item dropped:', event);
    
    // Get the component identifier from the drag event
    const componentType = event.dataTransfer ? event.dataTransfer.getData('widgetIdentifier') : '';
    console.log('Component type dropped:', componentType);
    
    if (componentType) {
      this.addComponentToDashboard(componentType);
    } else {
      console.log('No component type found in drag data');
    }
  }
  
  // Add a new component to the dashboard
  addComponentToDashboard(componentType: string) {
    // Generate a new ID for the component
    const newId = this.dashboard.length > 0 ? Math.max(...this.dashboard.map(item => item.id), 0) + 1 : 1;
    
    let newItem: ShieldDashboardItem;
    
    switch (componentType) {
      case "bar_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'bar-chart', 
          name: 'Bar Chart', 
          id: newId
        };
        break;
      case "doughnut_chart":
        // For doughnut charts, we'll need to determine which one based on existing items
        const donutCount = this.dashboard.filter(item => item.chartType === 'donut-chart').length;
        if (donutCount % 2 === 0) {
          newItem = { 
            cols: 5, 
            rows: 6, 
            y: 0, 
            x: 0, 
            chartType: 'donut-chart', 
            name: 'End Customer Donut', 
            id: newId
          };
        } else {
          newItem = { 
            cols: 5, 
            rows: 6, 
            y: 0, 
            x: 0, 
            chartType: 'donut-chart', 
            name: 'Segment Penetration Donut', 
            id: newId
          };
        }
        break;
      case "map_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'map-chart', 
          name: 'Map Chart', 
          id: newId
        };
        break;
      case "grid_view":
        newItem = { 
          cols: 10, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'data-table', 
          name: 'Data Table', 
          id: newId
        };
        break;
      case "to_do_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'deal-details', 
          name: 'Deal Details', 
          id: newId
        };
        break;
      case "line_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'quarterwise-flow', 
          name: 'Quarterwise Flow', 
          id: newId
        };
        break;
      default:
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: componentType, 
          name: componentType, 
          id: newId
        };
    }
    
    // Add the new item to the dashboard
    this.dashboard.push(newItem);
  }

  removeItem(item: ShieldDashboardItem) {
    // Add the item to deleted items list before removing
    this.deletedItems.push({...item});
    
    // Remove the item from the dashboard
    this.dashboard.splice(this.dashboard.indexOf(item), 1);
  }
  
  // Restore a deleted item
  restoreItem(item: ShieldDashboardItem) {
    // Remove from deleted items
    this.deletedItems.splice(this.deletedItems.indexOf(item), 1);
    
    // Add back to dashboard
    this.dashboard.push(item);
  }
  
  // Clear all deleted items
  clearDeletedItems() {
    this.deletedItems = [];
  }

  itemChange() {
    console.log('Item changed:', this.dashboard);
  }
  
  itemResize(item: any, itemComponent: any) {
    console.log('Item resized:', item);
    // Trigger a window resize event to notify charts to resize
    window.dispatchEvent(new Event('resize'));
  }
  
  /**
   * Extract only the relevant chart configuration properties to pass to chart components
   * This prevents errors when trying to set properties that don't exist on the components
   */
  getChartInputs(item: any): any {
    // Only pass properties that are relevant to chart components
    const chartInputs = {
      chartType: item.chartType,
      name: item.name
    };
    
    // Remove undefined properties to avoid passing unnecessary data
    Object.keys(chartInputs).forEach(key => {
      if (chartInputs[key] === undefined) {
        delete chartInputs[key];
      }
    });
    
    return chartInputs;
  }
}