import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router-dom";

const GridRunnerComponent = ({ dashboardService, dashRunnerService }) => {
  const { id } = useParams(); // React Router for route parameters
  const contentContainerRef = useRef(null);
  const [rows, setRows] = useState([]);
  const [editId, setEditId] = useState(null);
  const [workflowLine, setWorkflowLine] = useState(null);
  const [tableName, setTableName] = useState(null);
  const [xAxis, setXAxis] = useState(null);
  const [yAxis, setYAxis] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setEditId(id);

    dashboardService.getById(id).then((data) => {
      const lineData = data?.dashbord1_Line?.[0]?.model;
      setWorkflowLine(lineData);

      const dash = JSON.parse(lineData || "{}");
      const chartObjects = dash.dashboard?.filter(
        (obj) => obj.name === "Grid View"
      ) || [];

      chartObjects.forEach((chartObject) => {
        const ids = dashRunnerService.getGridView();
        if (!ids.includes(chartObject.chartid)) {
          dashRunnerService.setGridView(chartObject.chartid);

          if (chartObject.chartid === ids[0]) {
            setTableName(chartObject.table);
            setXAxis(chartObject.xAxis);
            setYAxis(chartObject.yAxis);

            dashRunnerService
              .getChartData(chartObject.table, "Grid View", chartObject.xAxis, chartObject.yAxis)
              .then((data) => {
                setRows(data);
              })
              .catch((error) => console.error("Error fetching chart data:", error));
          }
        }
      });
    });
  }, [id, dashboardService, dashRunnerService]);

  const getHeaders = () => {
    if (!rows || rows.length === 0) return [];
    return Object.keys(rows[0]);
  };

  const generatePDFFile = () => {
    if (!contentContainerRef.current) return;
    const content = contentContainerRef.current;
    const filename = "gridview.pdf";
    dashRunnerService.generatePDF(content, filename);
  };

  return (
    <div>
      <button className="btn btn-primary" onClick={generatePDFFile}>
        Export
      </button>
      <div style={{ maxHeight: "400px", overflow: "auto", padding: "10px" }}>
        <table className="table">
          <thead>
            <tr>
              {getHeaders().map((header, index) => (
                <th key={index}>{header}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.slice().reverse().map((row, rowIndex) => (
              <tr key={rowIndex}>
                {getHeaders().map((key, colIndex) => (
                  <td key={colIndex}>{row[key]}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default GridRunnerComponent;
