import React, { useEffect, useRef, useState } from 'react';
import { Chart as ChartJS, registerables } from 'chart.js';
import { Scatter } from 'react-chartjs-2';

ChartJS.register(...registerables);

const ScatterRunner = ({ dashboardService, dashrunnerService, routeParams }) => {
  const contentContainerRef = useRef(null);
  const [scatterChartData, setScatterChartData] = useState([]);
  const [scatterChartLabels, setScatterChartLabels] = useState([]);
  const [chartLegend, setChartLegend] = useState(false);
  const [editId, setEditId] = useState(routeParams.id || null);

  const chartOptions = {
    responsive: true,
    aspectRatio: 2.5,
  };

  const scatterChartDataTemplate = {
    datasets: [
      {
        data: [
          { x: 1, y: 1 },
          { x: 2, y: 3 },
          { x: 3, y: -2 },
          { x: 4, y: 4 },
          { x: 5, y: -3, r: 20 },
        ],
        label: 'Series A',
        pointRadius: 10,
        backgroundColor: 'red',
      },
      {
        data: [
          { x: 2, y: 2 },
          { x: 3, y: 4 },
          { x: 4, y: -1 },
          { x: 5, y: 5 },
          { x: 6, y: -2, r: 20 },
        ],
        label: 'Series B',
        pointRadius: 10,
        backgroundColor: 'blue',
      },
    ],
  };

  useEffect(() => {
    if (editId) {
      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 === 'Scatter Chart');

        chartObject.forEach((chart) => {
          const ids = dashrunnerService.getscatterchart();
          if (!ids.includes(chart.chartid)) {
            dashrunnerService.setscatterchart(chart.chartid);

            dashrunnerService
              .getChartData(chart.table, 'Scatter Chart', chart.xAxis, chart.yAxis)
              .then((chartData) => {
                setScatterChartData(chartData.scatterChartData);
                setScatterChartLabels(chartData.scatterChartLabels);
                setChartLegend(chart.chartlegend);
              })
              .catch((error) => console.error(error));
          }
        });
      });
    }
  }, [editId, dashboardService, dashrunnerService]);

  const generatePDFFile = () => {
    if (contentContainerRef.current) {
      const content = contentContainerRef.current;
      const filename = 'scatterchart.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}>
        <Scatter
          data={{
            labels: scatterChartLabels,
            ...scatterChartDataTemplate,
          }}
          options={chartOptions}
        />
      </div>
    </div>
  );
};

export default ScatterRunner;
