import React, { useEffect, useRef, useState } from 'react';
import { PolarArea } from 'react-chartjs-2';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import axios from 'axios';

const PolarRunnerComponent = ({ match }) => {
  const [editId, setEditId] = useState(null);
  const [polarAreaChartLabels, setPolarAreaChartLabels] = useState([
    'Download Sales',
    'In-Store Sales',
    'Mail Sales',
    'Telesales',
    'Corporate Sales',
  ]);
  const [polarAreaChartData, setPolarAreaChartData] = useState([300, 500, 100, 40, 120]);
  const [chartLegend, setChartLegend] = useState(false);
  const [tableName, setTableName] = useState('');
  const [xAxis, setXAxis] = useState('');
  const [yAxis, setYAxis] = useState('');
  const [showLabel, setShowLabel] = useState(true);
  const [jsonData, setJsonData] = useState(null);

  const contentContainerRef = useRef(null);

  useEffect(() => {
    const id = match.params.id;
    setEditId(id);

    axios.get(`/api/dashboard/${id}`).then((response) => {
      const data = response.data;
      const workflowLine = data.dashbord1_Line[0].model;
      const dash = JSON.parse(workflowLine);

      const chartObject = dash.dashboard.filter((obj) => obj.name === 'Polar Area Chart');
      chartObject.forEach((chart) => {
        if (chart.chartid) {
          setTableName(chart.table);
          setXAxis(chart.xAxis);
          setYAxis(chart.yAxis);
          setShowLabel(chart.showlabel);
          setChartLegend(chart.chartlegend);

          axios
            .get(`/api/chart-data`, {
              params: {
                tableName: chart.table,
                chartType: 'PolarArea Chart',
                xAxis: chart.xAxis,
                yAxis: chart.yAxis,
              },
            })
            .then((chartData) => {
              setJsonData(chartData.data);
              setPolarAreaChartData(chartData.data.polarAreaChartData);
              setPolarAreaChartLabels(chartData.data.polarAreaChartLabels);
            })
            .catch((err) => console.error(err));
        }
      });
    });
  }, [match.params.id]);

  const generatePDFFile = () => {
    const content = contentContainerRef.current;
    if (content) {
      html2canvas(content).then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save('polarareachart.pdf');
      });
    }
  };

  const chartData = {
    labels: polarAreaChartLabels,
    datasets: [
      {
        data: polarAreaChartData,
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'],
      },
    ],
  };

  return (
    <div>
      <button className="btn btn-primary" onClick={generatePDFFile}>
        Export
      </button>
      <div className="chart-box" id="contentContainer" ref={contentContainerRef}>
        <PolarArea data={chartData} options={{ plugins: { legend: { display: chartLegend } } }} />
      </div>
    </div>
  );
};

export default PolarRunnerComponent;
