import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import Chart from 'chart.js/auto';
import axios from 'axios';

const BarRunnerComponent = ({ onButtonClicked }) => {
  const contentContainerRef = useRef(null);
  const { id: editId } = useParams();

  const [barChartData, setBarChartData] = useState([]);
  const [barChartLabels, setBarChartLabels] = useState([]);
  const [barChartLegend, setBarChartLegend] = useState(false);
  const [tableName, setTableName] = useState('');
  const [xAxis, setXAxis] = useState('');
  const [yAxis, setYAxis] = useState('');
  const [showLabel, setShowLabel] = useState(false);
  const [jsonData, setJsonData] = useState(null);

  const charData = {
    barChartData: [{ data: [45, 37, 60, 70, 46, 33], label: 'Best Fruits' }],
    barChartLabels: ['Apple', 'Banana', 'Kiwifruit', 'Blueberry', 'Orange', 'Grapes'],
  };

  useEffect(() => {
    setBarChartData(charData.barChartData);
    setBarChartLabels(charData.barChartLabels);

    const fetchData = async () => {
      try {
        const response = await axios.get(`/dashboard/${editId}`);
        const workflowLine = response.data.dashbord1_Line[0].model;
        const dash = JSON.parse(workflowLine);
        const chartObject = dash.dashboard.filter(obj => obj.name === 'Bar Chart');

        for (let i = 0; i < chartObject.length; i++) {
          const ids = getBarChartIds();

          if (!ids.includes(chartObject[i].chartid)) {
            addBarChartId(chartObject[i].chartid);

            setTableName(chartObject[i].table);
            setXAxis(chartObject[i].xAxis);
            setYAxis(chartObject[i].yAxis);
            setShowLabel(chartObject[i].showlabel);
            setBarChartLegend(chartObject[i].chartlegend);

            const chartData = await getChartData(
              chartObject[i].table,
              'Bar Chart',
              chartObject[i].xAxis,
              chartObject[i].yAxis
            );

            setJsonData(chartData);
            setBarChartData(chartData.barChartData);
            setBarChartLabels(chartData.barChartLabels);
            break;
          }
        }
      } catch (error) {
        console.error(error);
      }
    };

    fetchData();
  }, [editId]);

  const generatePDFFile = () => {
    if (onButtonClicked) onButtonClicked();

    const content = contentContainerRef.current;
    const filename = 'barchart.pdf';
    generatePDF(content, filename);
  };

  // Placeholder functions for service calls (replace these with actual API logic)
  const getBarChartIds = () => [];
  const addBarChartId = id => console.log(`Added chart id: ${id}`);
  const getChartData = async (table, type, xAxis, yAxis) => {
    // Replace with actual API call
    console.log(`Fetching chart data for table: ${table}, type: ${type}`);
    return charData;
  };
  const generatePDF = (content, filename) => {
    console.log(`Generating PDF for ${filename} with content:`, content);
    // Add logic for PDF generation
  };

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

export default BarRunnerComponent;
