import { useState, useCallback, useEffect } from 'react';

import Card from '@mui/material/Card';
import { useTheme } from '@mui/material/styles';
import CardHeader from '@mui/material/CardHeader';

import { Chart, useChart, ChartSelect } from 'src/components/chart';

// ----------------------------------------------------------------------

export function CourseHoursSpent({ title, subheader, chart, onValueChange, value, ...other }) {
  const theme = useTheme();

  // Если пропс value передан, используем его, иначе внутреннее состояние
  const [internalSeries, setInternalSeries] = useState(chart.series[0]?.name || 'Месяц');
  
  const selectedSeries = value !== undefined ? value : internalSeries;

  const currentSeries = chart.series.find((i) => i.name === selectedSeries) || chart.series[0];

  const chartColors = chart.colors ?? [theme.palette.text.primary, theme.palette.info.main];

  const chartOptions = useChart({
    grid: { padding: { left: 24 } },
    stroke: { width: 3, curve: 'smooth' },
    colors: chartColors,
    xaxis: { 
      categories: currentSeries?.data[0]?.categories || [] 
    },
    ...chart.options,
  });

  const handleChangeSeries = useCallback((newValue) => {
    if (value === undefined) {
      setInternalSeries(newValue);
    }
    if (onValueChange) {
      onValueChange(newValue);
    }
  }, [onValueChange, value]);

  return (
    <Card {...other}>
      <CardHeader
        title={title}
        subheader={subheader}
        action={
          <ChartSelect
            options={chart.series.filter(s => s.name !== '').map((item) => item.name)}
            value={selectedSeries}
            onChange={handleChangeSeries}
          />
        }
        sx={{ mb: 3 }}
      />

      <Chart
        type="line"
        series={currentSeries?.data}
        options={chartOptions}
        height={320}
        loadingProps={{ sx: { p: 2.5 } }}
        sx={{ py: 2.5, pl: 1, pr: 2.5 }}
      />
    </Card>
  );
}
