import React, { useEffect, useState, useRef } from 'react';
import { Doughnut } from 'react-chartjs-2';
import { useParams, useNavigate } from 'react-router-dom';
import { jsPDF } from 'jspdf';
import DashrunnerService from '../services/DashrunnerService'; // Replace with actual service
import Dashboard3Service from '../services/Dashboard3Service'; // Replace with actual service

const DoughnutRunner = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const contentContainerRef = useRef(null);

  const [doughnutChartData, setDoughnutChartData] = useState([]);
  const [doughnutChartLabels, setDoughnutChartLabels] = useState([]);
  const [doughnutChartLegend, setDoughnutChartLegend] = useState(false);
  const [showlabel, setShowlabel] = useState(true);
  const [TableName, setTableName] = useState('');
  const [XAxis, setXAxis] = useState('');
  const [YAxis, setYAxis] = useState('');
  const [workflowLine, setWorkflowLine] = useState(null);

  useEffect(() => {
    Dashboard3Service.getById(id).then((data) => {
      const workflow = data.dashbord1_Line[0]?.model;
      const parsedData = JSON.parse(workflow);
      const chartObjects = parsedData.dashboard.filter(
        (obj) => obj.name === 'Doughnut Chart'
      );

      for (let chartObject of chartObjects) {
        const ids = DashrunnerService.getDoughnutChartIds();
        if (ids.includes(chartObject.chartid)) continue;

        DashrunnerService.setDoughnutChart(chartObject.chartid);

        setTableName(chartObject.table);
        setXAxis(chartObject.xAxis);
        setYAxis(chartObject.yAxis);
        setShowlabel(chartObject.showlabel);
        setDoughnutChartLegend(chartObject.chartlegend);

        DashrunnerService.getChartData(
          chartObject.table,
          'Doughnut Chart',
          chartObject.xAxis,
          chartObject.yAxis
        ).then((chartData) => {
          setDoughnutChartData(chartData.chartData);
          setDoughnutChartLabels(chartData.chartLabels);
        });
        break;
      }
    });
  }, [id]);

  const generatePDFFile = () => {
    const content = contentContainerRef.current;
    const pdf = new jsPDF();
    pdf.html(content, {
      callback: (doc) => {
        doc.save('doughnut.pdf');
      },
    });
  };

  return (
    <div>
      <div style={{ textAlign: 'right' }}>
        <button className="btn btn-primary" onClick={generatePDFFile}>
          Export
        </button>
      </div>
      <div className="chart-box" ref={contentContainerRef}>
        <Doughnut
          data={{
            labels: showlabel ? doughnutChartLabels : [],
            datasets: [
              {
                data: doughnutChartData[0] || [],
                backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
              },
            ],
          }}
          options={{
            legend: {
              display: doughnutChartLegend,
            },
          }}
        />
      </div>
    </div>
  );
};

export default DoughnutRunner;
