// DynamicChart.js
import React, { useState } from 'react';
import { Bar } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

// 

const DynamicChart = () => {
  const [chartType, setChartType] = useState('bar');

  const barChartOptions = {
    responsive: true,
    plugins: {
      legend: {
        display: true,
      },
      title: {
        display: true,
        text: 'Dynamic Chart',
      },
    },
  };

  const dynamicChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];

  const dynamicChartData = {
    labels: dynamicChartLabels,
    datasets: [
      { data: [65, 59, 90, 81, 56, 55, 40], label: 'Series A', backgroundColor: 'rgba(75, 192, 192, 0.6)' },
      { data: [28, 48, 40, 19, 96, 27, 100], label: 'Series B', backgroundColor: 'rgba(153, 102, 255, 0.6)' },
    ],
  };

  const handleChartClick = (event, elements) => {
    if (elements.length > 0) {
      const { index } = elements[0].element.$context;
      console.log(`Clicked on:`, dynamicChartLabels[index]);
    }
  };

  const handleChartHover = (event, elements) => {
    if (elements.length > 0) {
      console.log('Hovered over:', elements);
    }
  };

  const randomize = () => {
    setChartType((prevType) => (prevType === 'bar' ? 'line' : 'bar'));
  };

  return (
    <div style={{ display: 'block', width: '800px', margin: 'auto' }}>
      <Bar
        data={dynamicChartData}
        options={barChartOptions}
        type={chartType}
        onClick={(event, elements) => handleChartClick(event, elements)}
        onHover={(event, elements) => handleChartHover(event, elements)}
      />
      <button
        className="btn btn-primary"
        style={{ marginTop: '20px' }}
        onClick={randomize}
      >
        Update
      </button>
    </div>
  );
};

export default DynamicChart;
