import React, { useState, useEffect, useRef } from "react";
import { Chart } from "chart.js";
import { jsPDF } from "jspdf";
import domtoimage from "dom-to-image";

const LineRunnerComponent = ({ dashrunnerService, dashboardService }) => {
  const contentContainerRef = useRef(null);
  const [lineChartData, setLineChartData] = useState([]);
  const [lineChartLabels, setLineChartLabels] = useState([]);
  const [lineChartNoLabels] = useState([]);
  const [lineChartLegend, setLineChartLegend] = useState(false);
  const [workflowLine, setWorkflowLine] = useState(null);
  const [tableName, setTableName] = useState(null);
  const [xAxis, setXAxis] = useState(null);
  const [yAxis, setYAxis] = useState(null);
  const [showLabel, setShowLabel] = useState(null);
  const [editId, setEditId] = useState(null);

  useEffect(() => {
    // Mock equivalent of Angular's ActivatedRoute for id retrieval
    const idFromRoute = "mockId"; // Replace with actual route logic
    setEditId(idFromRoute);

    dashboardService.getById(idFromRoute).then((data) => {
      const workflow = data.dashbord1_Line[0].model;
      setWorkflowLine(workflow);

      const parsedData = JSON.parse(workflow);
      const chartObjects = parsedData.dashboard.filter(
        (obj) => obj.name === "Line Chart"
      );

      chartObjects.forEach((chart) => {
        const ids = dashrunnerService.getlinechart();
        if (!ids.includes(chart.chartid)) {
          dashrunnerService.setlinechart(chart.chartid);

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

            dashrunnerService
              .getChartData(chart.table, "Line Chart", chart.xAxis, chart.yAxis)
              .then((Ldata) => {
                setLineChartData(Ldata.chartData);
                setLineChartLabels(Ldata.chartLabels);
              })
              .catch((error) => console.error(error));
          }
        }
      });
    });
  }, [dashrunnerService, dashboardService]);

  const generatePDFFile = () => {
    const content = contentContainerRef.current;
    const filename = "linechart.pdf";

    dashrunnerService.generatePDF(content, filename);
  };

  return (
    <div>
      <button className="btn btn-primary" onClick={generatePDFFile}>
        Export
      </button>
      <div className="chart-box" id="contentContainer" ref={contentContainerRef}>
        <canvas
          id="lineChart"
          style={{ display: "block" }}
        ></canvas>
      </div>
    </div>
  );
};

export default LineRunnerComponent;
