import React, { useState, useEffect, useRef } from 'react';

const PieRunnerComponent = ({ editId, onButtonClicked, dashRunnerService, dashboardService }) => {
  const contentContainerRef = useRef(null);
  const [pieChartLabels, setPieChartLabels] = useState(['SciFi', 'Drama', 'Comedy']);
  const [pieChartData, setPieChartData] = useState([30, 50, 20]);
  const [chartLegend, setChartLegend] = useState(false);
  const [tableName, setTableName] = useState('');
  const [xAxis, setXAxis] = useState('');
  const [yAxis, setYAxis] = useState('');
  const [showLabel, setShowLabel] = useState(false);
  const [jsonData, setJsonData] = useState(null);

  useEffect(() => {
    if (!editId) return;

    dashboardService.getById(editId).then((data) => {
      const workflowLine = data.dashbord1_Line[0].model;
      const dash = JSON.parse(workflowLine);

      const chartObject = dash.dashboard.filter((obj) => obj.name === 'Pie Chart');
      chartObject.forEach((chart) => {
        const ids = dashRunnerService.getPieChart();
        if (ids.includes(chart.chartid)) return;

        dashRunnerService.setPieChart(chart.chartid);

        if (chart.chartid === ids[0]) {
          setTableName(chart.table);
          setXAxis(chart.xAxis);
          setYAxis(chart.yAxis);
          setShowLabel(chart.showlabel);
          setChartLegend(chart.chartlegend);

          dashRunnerService.getChartData(chart.table, 'Pie Chart', chart.xAxis, chart.yAxis).then((Ldata) => {
            setJsonData(Ldata);
            setPieChartLabels(Ldata.pieChartLabels);
            setPieChartData(Ldata.pieChartData);
          }).catch((error) => {
            console.error('Error fetching chart data:', error);
          });
        }
      });
    });
  }, [editId, dashRunnerService, dashboardService]);

  const generatePDFFile = () => {
    if (onButtonClicked) {
      onButtonClicked();
    }
    const content = contentContainerRef.current;
    const filename = 'piechart.pdf';

    dashRunnerService.generatePDF(content, filename);
  };

  return (
    <div>
      <div>
        <button className="btn btn-primary" onClick={generatePDFFile}>
          Export
        </button>
      </div>
      <div className="chart-box" id="contentContainer" ref={contentContainerRef}>
        <canvas
          style={{ display: 'block', width: '238px', height: '200px' }}
        >
          {/* Replace with a React chart library like 'react-chartjs-2' */}
          <p>Pie chart will render here using labels and data.</p>
        </canvas>
      </div>
    </div>
  );
};

export default PieRunnerComponent;
