import { DashboardStateService } from './../../services/state/dashboard-state.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChartConfiguration, ChartOptions } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import { GeneralService } from '../../services/generalservice';
import { IDropAct, IStateDrop, IActData, IActSumData } from '../../interfaces/dashboard.interface';


@Component({
  selector: 'app-main-dashboard-content',
  standalone: false,
  templateUrl: './main-dashboard-content.component.html',
  styleUrls: ['./main-dashboard-content.component.css']
})
export class MainDashboardContentComponent implements OnInit {
  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;
  myDropAct!: IStateDrop;
  myActData: IActData[] = [];
  myActSumData: IActSumData = {
    summary: {
      totalIncome: '',
      totalExpense: '',
      netProfit: '',
      profitRate: '',
      adjustedProfitRate: '',
      period: ''
    },
    pie: {
      income: [],
      expense: []
    }
  };

  constructor(
    private generalService: GeneralService,
    private dashboardStateService: DashboardStateService
  ) {}

  ngOnInit(): void {
    let token = localStorage.getItem('access_token')
    this.OnSearchAct(token, true);
    this.OnSetupDashboard(token, true);
    this.OnSearchSum(token, true);
  }

  OnSearchAct(value: any, setupFirst: boolean): void {
    const uri = '/api/web/accountingSearch';
    let request = {
      token: value
    }
    this.generalService.postRequest(uri, request).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          this.generalService.trowApi(result);
          this.myActData = result.data;
          this.dashboardStateService.setStateAccountResult(this.myActData);
        }else{
          this.generalService.trowApi(result);
        }
      },
      error: (error: any) => {
        this.generalService.trowApi(error);
      },
      complete: () => {

      }
    });
  }



  OnSetupDashboard(value: any, setupFirst: boolean): void {
    const uri = '/api/web/accountingSetup';
    let request = {
      token: value
    }
    this.generalService.postRequest(uri, request).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          this.generalService.trowApi(result);
          this.myDropAct = result.data
          this.dashboardStateService.setStateResult(this.myDropAct)
        }else{
          this.generalService.trowApi(result);
        }
      },
      error: (error: any) => {
        this.generalService.trowApi(error);
      },
      complete: () => {

      }
    });
  }

  OnSearchSum(value: any, setupFirst: boolean): void {
    const uri = '/api/web/accountingSum';
    let request = {
      token: value
    }
    this.generalService.postRequest(uri, request).subscribe({
      next: (result: any) => {
        if (result.code === '200') {
          this.generalService.trowApi(result);
          this.myActSumData = result.data
          this.dashboardStateService.setStateSumResult(this.myActSumData);
        }else{
          this.generalService.trowApi(result);
        }
      },
      error: (error: any) => {
        this.generalService.trowApi(error);
      },
      complete: () => {

      }
    });
  }

  // fetchChartData(): void {
  //   // NOTE: Using a placeholder endpoint as the actual one was not provided.
  //   const uri = '/api/dashboard/summary-last-6-months';

  //   this.generalService.getRequest(uri).subscribe({
  //     next: (result: any) => {
  //       if (result.code === '200' && result.data) {
  //         this.processChartData(result.data);
  //       } else {
  //         console.warn('Could not fetch chart data:', result.message_th);
  //         // Optionally, display placeholder data or an error message
  //         this.setupPlaceholderData();
  //       }
  //     },
  //     error: (error: any) => {
  //       console.error('Error fetching chart data:', error);
  //       // Display placeholder data on error to show the graph structure
  //       this.setupPlaceholderData();
  //     }
  //   });
  // }

  // processChartData(data: any[]): void {
  //   const labels = data.map(item => item.month);
  //   const revenues = data.map(item => item.revenue);

  //   this.lineChartData.labels = labels;
  //   this.lineChartData.datasets[0].data = revenues;

  //   this.chart?.update();
  // }

  // setupPlaceholderData(): void {
  //   // This function is called if the API fails, to show a sample graph.
  //   const labels = ['January', 'February', 'March', 'April', 'May', 'June'];
  //   const revenues = [1200, 1900, 3000, 5000, 2300, 3200]; // Sample data

  //   this.lineChartData.labels = labels;
  //   this.lineChartData.datasets[0].data = revenues;

  //   this.chart?.update();
  // }
}
