import React, { useState } from 'react';
import { Box, Button } from '@mui/material';
import { Bar } from 'react-chartjs-2';
import { registerChartJS, commonChartOptions } from './chartutils';

registerChartJS();

const DynamicChart = () => {
  const [chartType, setChartType] = useState('bar');
  const labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];

  const data = {
    labels,
    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 options = {
    ...commonChartOptions,
    plugins: {
      legend: {
        display: true,
      },
      title: {
        display: true,
        text: 'Dynamic Chart',
      },
    },
  };

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

  return (
    <Box sx={{ height: 500 }}>
      <Bar 
        data={data} 
        options={options} 
        type={chartType} 
      />
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
        <Button variant="contained" onClick={randomize}>
          Toggle Chart Type
        </Button>
      </Box>
    </Box>
  );
};

export default DynamicChart;