import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { DashrunnerService } from '../dashrunner.service';
import { DashboardContentModel } from 'src/app/models/builder/dashboard';
import { ActivatedRoute, Router } from '@angular/router';
import { Dashboard3Service } from 'src/app/services/builder/dashboard3.service';
// Add FilterService import
import { FilterService } from '../../../dashboardnew/common-filter/filter.service';
// Add Subscription import
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-grid-runner',
  templateUrl: './grid-runner.component.html',
  styleUrls: ['./grid-runner.component.scss']
})
export class GridRunnerComponent implements OnInit {
  @ViewChild('contentContainer') contentContainerRef!: ElementRef;
  @Output() buttonClicked = new EventEmitter<void>();
  loading = false;
  givendata;
  error;
  XAxis;
  YAxis;

  rows:any[];
  columns: any[];
  rowdata;

  editId;
  public DashtestboardArray: DashboardContentModel[] = [];
  workflowLine;
  TableName;
  ConnectionId: number; // Add ConnectionId property
  
  // Add subscriptions to unsubscribe on destroy
  private subscriptions: Subscription[] = [];

  constructor(
    private Dashtestservive:DashrunnerService,
    private route: ActivatedRoute,
    private dashboardService: Dashboard3Service,
    private router : Router,
    // Add FilterService to constructor
    private filterService: FilterService
  ) { }

  ngOnInit(): void {

    this.editId = this.route.snapshot.params.id;
    console.log('GridRunner: Component initialized with editId:', this.editId);
    // this.getbyId();

    // Subscribe to filter changes
    this.subscriptions.push(
      this.filterService.filterState$.subscribe(filters => {
        console.log('GridRunner: Filter state changed:', filters);
        // When filters change, refresh the grid data
        this.fetchGridData();
      })
    );

    this.dashboardService.getById(this.editId).subscribe((data) => {
      console.log('GridRunner: Received dashboard data:', data);
      this.workflowLine = data.dashbord1_Line[0].model;
      const dash = JSON.parse(this.workflowLine);
      // this.DashtestboardArray = dash.dashboard;
      // console.log(this.DashtestboardArray);

      const ChartObject = dash.dashboard.filter(obj => obj.name === "Grid View");
      console.log('GridRunner: ChartObject for Grid View:', ChartObject);
      for (let i = 0; i < ChartObject.length; i++) {
        const ids = this.Dashtestservive.getgridview();
        console.log('GridRunner: Current gridview ids:', ids);
        console.log('GridRunner: Checking chartid:', ChartObject[i].chartid);
        // console.log(ids);
        if (ids.includes(ChartObject[i].chartid)) {
          // If the chartid is already in the ids array, continue to the next iteration
          console.log('GridRunner: Skipping chartid as it already exists:', ChartObject[i].chartid);
          continue;
        }
        console.log('GridRunner: Adding new chartid:', ChartObject[i].chartid);
        this.Dashtestservive.setgridview(ChartObject[i].chartid);

        this.TableName = ChartObject[i].table;
        this.XAxis = ChartObject[i].xAxis;
        this.YAxis = ChartObject[i].yAxis;
        // Add connection ID if available
        this.ConnectionId = ChartObject[i].connection;
        console.log('GridRunner: TableName:', this.TableName);
        console.log('GridRunner: XAxis:', this.XAxis);
        console.log('GridRunner: YAxis:', this.YAxis);
        console.log('GridRunner: ConnectionId:', this.ConnectionId);
        // Fetch data with filters
        this.fetchGridData();
        break; // No need to continue the loop once the correct placeholder is found
      }
    }, (error) => {
      console.log('GridRunner: Error fetching dashboard data:', error);
    });
  }

  // Fetch grid data with filter support
  fetchGridData(): void {
    console.log('fetching grid data ...')
    if (this.TableName) {
      console.log('GridRunner: Fetching data for TableName:', this.TableName, 'XAxis:', this.XAxis, 'YAxis:', this.YAxis);
      // Convert YAxis to string if it's an array
      const yAxisString = Array.isArray(this.YAxis) ? this.YAxis.join(',') : this.YAxis;

      // Get filter parameters from common filters
      const commonFilters = this.filterService.getFilterValues();
      const filterDefinitions = this.filterService.getFilters();

      // Build filter object using field names as keys
      const filterObj = {};
      Object.keys(commonFilters).forEach(filterId => {
        const filterValue = commonFilters[filterId];

        // Find the filter definition to get the field name
        const filterDef = this.filterService.getFilters().find(f => f.id === filterId);

        if (filterDef && filterDef.field) {
          const fieldName = filterDef.field;
          if (filterValue !== undefined && filterValue !== null && filterValue !== '') {
            filterObj[fieldName] = filterValue;
          }
        }
      });

      // Convert to JSON string for API call
      let filterParams = '';
      if (Object.keys(filterObj).length > 0) {
        filterParams = JSON.stringify(filterObj);
      }

      console.log('GridRunner: Final filter object to send to API:', filterObj);

      // Fetch data from the dashboard service with filters
      this.Dashtestservive.getChartDataWithFilters(this.TableName, "grid", this.XAxis, this.YAxis, this.ConnectionId, '', '', filterParams).subscribe((Ldata) => {
        console.log('GridRunner: Received data from API:', Ldata);

        // Handle the actual data structure returned by the API
        if (Ldata && Ldata.chartData) {
          this.rows = Ldata.chartData;
          this.rowdata = this.rows;
        } else if (Ldata && Ldata.data) {
          // Handle the original expected format as fallback
          this.rows = Ldata.data;
          this.rowdata = this.rows;
        } else if (Array.isArray(Ldata)) {
          // Handle case where data is directly an array
          this.rows = Ldata;
          this.rowdata = this.rows;
        } else {
          console.warn('GridRunner: Received data does not have expected structure', Ldata);
          this.rows = [];
          this.rowdata = [];
        }

        // Log the structure of the received data
        if (this.rows) {
          console.log('GridRunner: Rows length:', this.rows.length);
          if (this.rows.length > 0) {
            console.log('GridRunner: First row structure:', this.rows[0]);
          }
        } else {
          console.log('GridRunner: No data received');
        }
      }, (error) => {
        console.log('GridRunner: Error fetching data:', error);
        this.error = error;
      });
    } else {
      console.log('GridRunner: Missing TableName or XAxis');
    }
  }


  //dynamic table


  getTableData(id) {
  }
  getHeaders() {
    let headers: string[] = [];
    if (this.rows) {
      console.log('GridRunner: Getting headers from rows:', this.rows);
      this.rows.forEach((value) => {
        Object.keys(value).forEach((key) => {
          if (!headers.find((header) => header == key)) {
            headers.push(key)
          }
        })
      })
    }
    console.log('GridRunner: Computed headers:', headers);
    return headers;
  }

  generatePDFFile() {
    this.buttonClicked.emit();
    const content = this.contentContainerRef.nativeElement;
    const filename = 'gridview.pdf'; // You can provide any desired filename here

    this.Dashtestservive.generatePDF(content, filename);
  }

  ngOnDestroy() {
    // Unsubscribe from all subscriptions to prevent memory leaks
    console.log('GridRunnerComponent ngOnDestroy called, unsubscribing from', this.subscriptions.length, 'subscriptions');
    this.subscriptions.forEach(subscription => {
      if (subscription && !subscription.closed) {
        subscription.unsubscribe();
      }
    });
    this.subscriptions = [];

    console.log('GridRunnerComponent destroyed and cleaned up');
  }
}