import React, { useEffect, useRef, useState } from "react";
import { Chart as ChartJS, BubbleController, Tooltip, Legend, Title } from "chart.js";
import { Bubble } from "react-chartjs-2";
import { useParams } from "react-router-dom";

// Register Chart.js components
ChartJS.register(BubbleController, Tooltip, Legend, Title);

const BubbleRunnerComponent = ({ dashboardService, dashtestService }) => {
  const { id } = useParams(); // React Router hook to get route parameters
  const contentContainerRef = useRef(null);
  const [bubbleChartData, setBubbleChartData] = useState([]);
  const [chartLegend, setChartLegend] = useState(false);
  const [tableName, setTableName] = useState("");
  const [xAxis, setXAxis] = useState("");
  const [yAxis, setYAxis] = useState("");
  const [jsonData, setJsonData] = useState(null);

  const bubbleChartOptions = {
    plugins: {
      title: {
        display: true,
        text: "Bubble Chart",
      },
    },
    scales: {
      x: {
        min: 0,
        max: 30,
      },
      y: {
        min: 0,
        max: 30,
      },
    },
  };

  const fetchChartData = async (chartObject) => {
    const ids = dashtestService.getbubblechart();
    if (ids.includes(chartObject.chartid)) return;

    dashtestService.setbubblechart(chartObject.chartid);
    setTableName(chartObject.table);
    setXAxis(chartObject.xAxis);
    setYAxis(chartObject.yAxis);
    setChartLegend(chartObject.chartlegend);

    try {
      const data = await dashtestService.getChartData(chartObject.table, "Bubble Chart", chartObject.xAxis, chartObject.yAxis);
      setJsonData(data);
      setBubbleChartData(data.bubbleChartData);
    } catch (error) {
      console.error("Error fetching chart data:", error);
    }
  };

  useEffect(() => {
    const fetchWorkflowData = async () => {
      try {
        const data = await dashboardService.getById(id);
        const workflowLine = data.dashbord1_Line[0].model;
        const parsedWorkflow = JSON.parse(workflowLine);
        const chartObjects = parsedWorkflow.dashboard.filter((obj) => obj.name === "Bubble Chart");

        chartObjects.forEach(fetchChartData);
      } catch (error) {
        console.error("Error fetching workflow data:", error);
      }
    };

    fetchWorkflowData();
  }, [id, dashboardService, dashtestService]);

  const generatePDFFile = () => {
    if (!contentContainerRef.current) return;

    const content = contentContainerRef.current;
    const filename = "bubblechart.pdf";

    dashtestService.generatePDF(content, filename);
  };

  const chartData = {
    datasets: bubbleChartData.map((data) => ({
      data: data.data,
      label: data.label,
      backgroundColor: data.backgroundColor,
      borderColor: data.borderColor,
      hoverBackgroundColor: data.hoverBackgroundColor,
      hoverBorderColor: data.hoverBorderColor,
    })),
  };

  return (
    <div>
      <button className="btn btn-primary" onClick={generatePDFFile}>
        Export
      </button>
      <div className="chart-box" id="contentContainer" ref={contentContainerRef}>
        <Bubble data={chartData} options={bubbleChartOptions} />
      </div>
    </div>
  );
};

export default BubbleRunnerComponent;
