import React, { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import DashrunnerService from "../services/DashrunnerService";
import Dashboard3Service from "../services/Dashboard3Service";
import { Chart } from "chart.js";

const RadarRunner = () => {
  const { id: editId } = useParams(); // Get 'id' from URL
  const contentContainerRef = useRef(null);
  const [radarChartLabels, setRadarChartLabels] = useState([
    "Eating",
    "Drinking",
    "Sleeping",
    "Designing",
    "Coding",
    "Cycling",
    "Running",
  ]);
  const [radarChartData, setRadarChartData] = useState([
    { data: [65, 59, 90, 81, 56, 55, 40], label: "Series A" },
    { data: [28, 48, 40, 19, 96, 27, 100], label: "Series B" },
  ]);
  const [showLabel, setShowLabel] = useState(true);
  const [lineChartNoLabels, setLineChartNoLabels] = useState([]);
  const [chartLegend, setChartLegend] = useState(false);

  const fetchData = async () => {
    try {
      const data = await Dashboard3Service.getById(editId);
      const workflowLine = data.dashbord1_Line[0].model;
      const parsedData = JSON.parse(workflowLine);

      const chartObject = parsedData.dashboard.filter(
        (obj) => obj.name === "Radar Chart"
      );

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

        DashrunnerService.setRadarChart(chart.chartid);

        if (chart.chartid === ids[0]) {
          const { table, xAxis, yAxis, showlabel, chartlegend } = chart;
          setChartLegend(chartlegend);
          setShowLabel(showlabel);

          const chartData = await DashrunnerService.getChartData(
            table,
            "Radar Chart",
            xAxis,
            yAxis
          );
          setRadarChartData(chartData.radarChartData);
          setRadarChartLabels(chartData.radarChartLabels);
          break;
        }
      }
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const generatePDFFile = () => {
    const content = contentContainerRef.current;
    const filename = "radarchart.pdf";
    DashrunnerService.generatePDF(content, filename);
  };

  useEffect(() => {
    fetchData();
  }, [editId]);

  return (
    <div>
      <div>
        <button className="btn btn-primary" onClick={generatePDFFile}>
          Export
        </button>
      </div>
      <div className="chart-box" id="contentContainer" ref={contentContainerRef}>
        <canvas
          id="radarChart"
          style={{ display: "block", width: "238px", height: "200px" }}
        ></canvas>
      </div>
    </div>
  );
};

export default RadarRunner;
