import { Component, OnInit } from '@angular/core';
import { GridsterConfig, GridsterItem } from 'angular-gridster2';
import { FormBuilder, FormGroup } from '@angular/forms';
import { DatastoreService } from 'src/app/services/fnd/datastore.service';
import { AlertsService } from 'src/app/services/fnd/alerts.service';
import { SureconnectService } from '../../sureconnect/sureconnect.service';

interface ShieldDashboardItem extends GridsterItem {
  chartType: string;
  name: string;
  id: number;
  component?: any;
  // Configuration properties
  charttitle?: string;
  connection?: string;
  table?: string;
  xAxis?: string;
  yAxis?: string[];
  chartlegend?: boolean;
  showlabel?: boolean;
  baseFilters?: any[];
  drilldownEnabled?: boolean;
  drilldownApiUrl?: string;
  drilldownXAxis?: string;
  drilldownYAxis?: string;
  drilldownParameter?: string;
  drilldownFilters?: any[];
  drilldownLayers?: any[];
}

interface WidgetModel {
  name: string;
  identifier: string;
}

@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>;
  
  // Configuration modal
  configModalOpen = false;
  modeledit = false; // Add this to match the main dashboard pattern
  configForm: FormGroup;
  selectedItem: ShieldDashboardItem | null = null;
  
  // Component palette
  showComponentPalette = false;
  WidgetsMock: WidgetModel[] = [
    {
      name: 'Bar Chart',
      identifier: 'bar_chart'
    },
    {
      name: 'Doughnut Chart',
      identifier: 'doughnut_chart'
    },
    {
      name: 'Map Chart',
      identifier: 'map_chart'
    },
    {
      name: 'Data Table',
      identifier: 'grid_view'
    },
    {
      name: 'Deal Details',
      identifier: 'to_do_chart'
    },
    {
      name: 'Quarterwise Flow',
      identifier: 'line_chart'
    },
    {
      name: 'Compact Filter',
      identifier: 'compact_filter'
    }
  ];
  
  // Services data
  storedata: any[] = [];
  columnData: any[] = [];
  sureconnectData: any[] = [];
  drilldownColumnData: any[] = [];
  layerColumnData: { [key: number]: any[] } = {};
  
  // Keep track of deleted items
  deletedItems: Array<ShieldDashboardItem> = [];

  constructor(
    private _fb: FormBuilder,
    private datastoreService: DatastoreService,
    private alertService: AlertsService,
    private sureconnectService: SureconnectService
  ) { }

  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 = [];
    
    // Initialize form
    this.configForm = this._fb.group({
      charttitle: [''],
      connection: [''],
      table: [''],
      xAxis: [''],
      yAxis: [''],
      chartlegend: [true],
      showlabel: [true]
    });
    
    // Load service data
    this.loadServicesData();
  }
  
  // Load initial data from services
  loadServicesData() {
    // Load sureconnect data
    this.sureconnectService.getAll().subscribe((data: any[]) => {
      this.sureconnectData = data;
    });
    
    // Load datastore data
    this.datastoreService.getAll().subscribe((data) => {
      this.storedata = data as any[];
    });
  }
  
  // Toggle component palette visibility
  toggleComponentPalette(): void {
    this.showComponentPalette = !this.showComponentPalette;
  }
  
  // Handle drag start event for components - matching the working implementation
  onDrag(event: DragEvent, identifier: string): void {
    console.log("on drag", identifier);
    console.log("on drag ", event);
    if (event.dataTransfer) {
      event.dataTransfer.setData('widgetIdentifier', identifier);
    }
  }

  onDrop(ev: any) {
    // Handle dropping new components onto the dashboard
    console.log('Item dropped:', ev);
    
    // Get the component identifier from the drag event
    const componentType = ev.dataTransfer ? ev.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,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        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,
            chartlegend: true,
            showlabel: true,
            baseFilters: [],
            drilldownEnabled: false,
            drilldownLayers: []
          };
        } else {
          newItem = { 
            cols: 5, 
            rows: 6, 
            y: 0, 
            x: 0, 
            chartType: 'donut-chart', 
            name: 'Segment Penetration Donut', 
            id: newId,
            chartlegend: true,
            showlabel: true,
            baseFilters: [],
            drilldownEnabled: false,
            drilldownLayers: []
          };
        }
        break;
      case "map_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'map-chart', 
          name: 'Map Chart', 
          id: newId,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        break;
      case "grid_view":
        newItem = { 
          cols: 10, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'data-table', 
          name: 'Data Table', 
          id: newId,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        break;
      case "to_do_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'deal-details', 
          name: 'Deal Details', 
          id: newId,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        break;
      case "line_chart":
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: 'quarterwise-flow', 
          name: 'Quarterwise Flow', 
          id: newId,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        break;
      case "compact_filter":
        newItem = { 
          cols: 3, 
          rows: 2, 
          y: 0, 
          x: 0, 
          chartType: 'compact-filter', 
          name: 'Compact Filter', 
          id: newId,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
        break;
      default:
        newItem = { 
          cols: 5, 
          rows: 6, 
          y: 0, 
          x: 0, 
          chartType: componentType, 
          name: componentType, 
          id: newId,
          chartlegend: true,
          showlabel: true,
          baseFilters: [],
          drilldownEnabled: false,
          drilldownLayers: []
        };
    }
    
    // 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,
      charttitle: item.charttitle,
      connection: item.connection,
      table: item.table,
      xAxis: item.xAxis,
      yAxis: item.yAxis,
      chartlegend: item.chartlegend,
      showlabel: item.showlabel,
      baseFilters: item.baseFilters || [],
      drilldownEnabled: item.drilldownEnabled,
      drilldownApiUrl: item.drilldownApiUrl,
      drilldownXAxis: item.drilldownXAxis,
      drilldownYAxis: item.drilldownYAxis,
      drilldownParameter: item.drilldownParameter,
      drilldownFilters: item.drilldownFilters || [],
      drilldownLayers: item.drilldownLayers || []
    };
    
    // Remove undefined properties to avoid passing unnecessary data
    Object.keys(chartInputs).forEach(key => {
      if (chartInputs[key] === undefined) {
        delete chartInputs[key];
      }
    });
    
    return chartInputs;
  }
  
  // Open configuration modal for a chart
  editGadget(item: ShieldDashboardItem) {
    console.log('Opening configuration modal for item:', item);
    this.selectedItem = item;
    this.modeledit = true; // Use modeledit instead of configModalOpen
    
    // Initialize form with item data
    this.configForm.patchValue({
      charttitle: item.charttitle || '',
      connection: item.connection || '',
      table: item.table || '',
      xAxis: item.xAxis || '',
      yAxis: item.yAxis || [],
      chartlegend: item.chartlegend !== undefined ? item.chartlegend : true,
      showlabel: item.showlabel !== undefined ? item.showlabel : true
    });
    
    console.log('Form values after patch:', this.configForm.value);
    
    // Load columns if table is set
    if (item.table) {
      this.getColumns(item.connection, item.table);
    }
    
    // Load drilldown columns if drilldown API URL is set
    if (item.drilldownApiUrl) {
      this.refreshDrilldownColumns();
    }
  }
  
  // Save configuration changes
  saveConfiguration() {
    if (this.selectedItem) {
      const formData = this.configForm.value;
      console.log('Saving configuration:', formData);
      
      // Update the selected item with form data
      Object.assign(this.selectedItem, formData);
      
      // Close the modal
      this.modeledit = false; // Use modeledit instead of configModalOpen
      this.selectedItem = null;
    }
  }
  
  // Cancel configuration changes
  cancelConfiguration() {
    console.log('Canceling configuration');
    this.modeledit = false; // Use modeledit instead of configModalOpen
    this.selectedItem = null;
  }
  
  // Get tables from datastore
  getTables(id: string) {
    this.alertService.getTablefromstore(parseInt(id, 10)).subscribe(gateway => {
      console.log(gateway);
      // Handle table data
    }, (error) => {
      console.log(error);
    });
  }
  
  // Get columns from API
  getColumns(connectionId: string, table: string) {
    const connId = connectionId ? parseInt(connectionId, 10) : undefined;
    this.alertService.getColumnfromurl(table, connId).subscribe(data => {
      console.log('Column data:', data);
      this.columnData = data;
    }, (error) => {
      console.log(error);
      this.columnData = [];
    });
  }
  
  // Refresh drilldown columns
  refreshDrilldownColumns() {
    if (this.selectedItem && this.selectedItem.drilldownApiUrl) {
      const connId = this.selectedItem.connection ? parseInt(this.selectedItem.connection, 10) : undefined;
      this.alertService.getColumnfromurl(this.selectedItem.drilldownApiUrl, connId).subscribe(data => {
        console.log('Drilldown column data:', data);
        this.drilldownColumnData = data;
      }, (error) => {
        console.log('Error fetching drilldown columns:', error);
        this.drilldownColumnData = [];
      });
    }
  }
  
  // Add base filter
  addBaseFilter() {
    if (this.selectedItem) {
      if (!this.selectedItem.baseFilters) {
        this.selectedItem.baseFilters = [];
      }
      this.selectedItem.baseFilters.push({ field: '', value: '' });
    }
  }
  
  // Remove base filter
  removeBaseFilter(index: number) {
    if (this.selectedItem && this.selectedItem.baseFilters) {
      this.selectedItem.baseFilters.splice(index, 1);
    }
  }
  
  // Add drilldown filter
  addDrilldownFilter() {
    if (this.selectedItem) {
      if (!this.selectedItem.drilldownFilters) {
        this.selectedItem.drilldownFilters = [];
      }
      this.selectedItem.drilldownFilters.push({ field: '', value: '' });
    }
  }
  
  // Remove drilldown filter
  removeDrilldownFilter(index: number) {
    if (this.selectedItem && this.selectedItem.drilldownFilters) {
      this.selectedItem.drilldownFilters.splice(index, 1);
    }
  }
  
  // Add drilldown layer
  addDrilldownLayer() {
    if (this.selectedItem) {
      if (!this.selectedItem.drilldownLayers) {
        this.selectedItem.drilldownLayers = [];
      }
      this.selectedItem.drilldownLayers.push({
        enabled: false,
        apiUrl: '',
        xAxis: '',
        yAxis: '',
        parameter: '',
        filters: []
      });
    }
  }
  
  // Remove drilldown layer
  removeDrilldownLayer(index: number) {
    if (this.selectedItem && this.selectedItem.drilldownLayers) {
      this.selectedItem.drilldownLayers.splice(index, 1);
    }
  }
  
  // Add layer filter
  addLayerFilter(layerIndex: number) {
    if (this.selectedItem && this.selectedItem.drilldownLayers) {
      const layer = this.selectedItem.drilldownLayers[layerIndex];
      if (layer) {
        if (!layer.filters) {
          layer.filters = [];
        }
        layer.filters.push({ field: '', value: '' });
      }
    }
  }
  
  // Refresh drilldown columns for a specific layer
  refreshDrilldownLayerColumns(layerIndex: number) {
    if (this.selectedItem && this.selectedItem.drilldownLayers && this.selectedItem.drilldownLayers[layerIndex]) {
      const layer = this.selectedItem.drilldownLayers[layerIndex];
      if (layer && layer.apiUrl) {
        const connId = this.selectedItem.connection ? parseInt(this.selectedItem.connection, 10) : undefined;
        this.alertService.getColumnfromurl(layer.apiUrl, connId).subscribe(data => {
          console.log(`Drilldown layer ${layerIndex} column data:`, data);
          // Store layer column data in the layerColumnData property
          this.layerColumnData[layerIndex] = data;
        }, (error) => {
          console.log(`Error fetching drilldown layer ${layerIndex} columns:`, error);
          this.layerColumnData[layerIndex] = [];
        });
      }
    }
  }
  
  // Remove layer filter
  removeLayerFilter(layerIndex: number, filterIndex: number) {
    if (this.selectedItem && this.selectedItem.drilldownLayers) {
      const layer = this.selectedItem.drilldownLayers[layerIndex];
      if (layer && layer.filters) {
        layer.filters.splice(filterIndex, 1);
      }
    }
  }
}