import React, { useEffect, useState } from 'react';
import { Rnd } from 'react-rnd';
import Highcharts from 'highcharts/highstock';
import HighchartsReact from 'highcharts-react-official';
import IndicatorsAll from 'highcharts/indicators/indicators-all';
import {
  Box,
  Button,
  IconButton,
  Typography,
  Paper,
  Grid,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import IndicatorSelector from './IndicatorSelector';

if (typeof Highcharts === 'object') {
  IndicatorsAll(Highcharts);
}

interface ChartOverlayProps {
  data: any[];
  symbol: string;
  selectedPreset: string | null;
  onClose: () => void;
  onPresetChange: (preset: string) => void;
  startDate: Date;
  endDate: Date;
}

const ChartOverlay: React.FC<ChartOverlayProps> = ({
  data,
  symbol,
  selectedPreset,
  onClose,
  onPresetChange,
  startDate,
  endDate,
}) => {
  const [position, setPosition] = useState({ x: 100, y: 100 });
  const [size, setSize] = useState({ width: 800, height: 600 });
  const [chartOptions, setChartOptions] = useState<Highcharts.Options>({});

  useEffect(() => {
    const savedPosition = localStorage.getItem('chartPosition');
    const savedSize = localStorage.getItem('chartSize');

    if (savedPosition) {
      setPosition(JSON.parse(savedPosition));
    }

    if (savedSize) {
      setSize(JSON.parse(savedSize));
    }

    updateChartOptions();
  }, [data, symbol, startDate, endDate]);

  const handleDragStop = (e: any, d: any) => {
    setPosition({ x: d.x, y: d.y });
    localStorage.setItem('chartPosition', JSON.stringify({ x: d.x, y: d.y }));
  };

  const handleResizeStop = (e: any, direction: any, ref: any, delta: any, position: any) => {
    setSize({ width: ref.style.width, height: ref.style.height });
    setPosition(position);
    localStorage.setItem('chartSize', JSON.stringify({ width: ref.style.width, height: ref.style.height }));
    localStorage.setItem('chartPosition', JSON.stringify(position));
  };

const updateChartOptions = () => {
  const newOptions: Highcharts.Options = {
    chart: {
      animation: {
        duration: 500
      },
    },
    title: {
      text: ${symbol} Price Chart,
    },
    rangeSelector: {
      selected: 2, // Default to 3M
      buttons: [{
        type: 'month',
        count: 1,
        text: '1M'
      }, {
        type: 'month',
        count: 3,
        text: '3M'
      }, {
        type: 'month',
        count: 6,
        text: '6M'
      }, {
        type: 'ytd',
        text: 'YTD'
      }, {
        type: 'year',
        count: 1,
        text: '1Y'
      }, {
        type: 'all',
        text: 'All'
      }]
    },
    navigator: {
      adaptToUpdatedData: true,
      series: {
        data: data
      }
    },
    xAxis: {
      type: 'datetime',
      ordinal: false,
    },
    yAxis: [{
      title: {
        text: 'Price',
      },
      height: '60%',
    }, {
      title: {
        text: 'Volume',
      },
      top: '65%',
      height: '35%',
      offset: 0,
    }],
    series: [{
      type: 'candlestick',
      id: 'mainSeries',
      name: symbol,
      data: data.map(item => [
        new Date(item.date).getTime(),
        item.open,
        item.high,
        item.low,
        item.close
      ]),
      connectNulls: true
    }, {
      type: 'column',
      id: 'volume',
      name: 'Volume',
      data: data.map(item => [
        new Date(item.date).getTime(),
        item.volume
      ]),
      yAxis: 1,
    }],
  };

  setChartOptions(newOptions);
};

  const handleApplyIndicator = (indicatorName: string, params: Record<string, number>) => {
    console.log('Applying indicator:', indicatorName, params);
    const newOptions = { ...chartOptions };

    newOptions.yAxis = newOptions.yAxis || [];
    newOptions.yAxis.push({
      title: {
        text: indicatorName.toUpperCase(),
      },
      height: '100%',
      top: ${newOptions.yAxis.length * 100}%,
      offset: 0,
      lineWidth: 2
    });

    newOptions.series = newOptions.series || [];
    newOptions.series.push({
      type: indicatorName,
      name: indicatorName.toUpperCase(),
      data: data,
      yAxis: newOptions.yAxis.length - 1,
      params: params
    });

    setChartOptions(newOptions);
  };

  const presets = ['1M', '3M', '6M', 'YTD', '1Y', 'All'];

  return (
    <Rnd
      style={{
        border: '1px solid #ccc',
        background: '#fff',
        overflow: 'hidden',
        borderRadius: '8px',
        zIndex: 1000,
      }}
      position={position}
      size={size}
      onDragStop={handleDragStop}
      onResizeStop={handleResizeStop}
      bounds="window"
      dragHandleClassName="drag-handle"
      resizeHandleClasses={{
        bottom: 'resizable-handle resizable-handle-s',
        bottomLeft: 'resizable-handle resizable-handle-sw',
        bottomRight: 'resizable-handle resizable-handle-se',
        left: 'resizable-handle resizable-handle-w',
        right: 'resizable-handle resizable-handle-e',
        top: 'resizable-handle resizable-handle-n',
        topLeft: 'resizable-handle resizable-handle-nw',
        topRight: 'resizable-handle resizable-handle-ne',
      }}
    >
      <Paper elevation={3} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Box
          className="drag-handle"
          display="flex"
          justifyContent="space-between"
          alignItems="center"
          p={2}
          sx={{
            cursor: 'move',
            backgroundColor: '#f5f5f5',
            borderBottom: '1px solid #ddd'
          }}
        >
          <Typography variant="h6">
            {symbol} Price Chart
          </Typography>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>

        <Box p={2} sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
          <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
            <Grid container spacing={1} alignItems="center">
              {presets.map((preset) => (
                <Grid item key={preset}>
                  <Button
                    variant={selectedPreset === preset ? "contained" : "outlined"}
                    onClick={() => onPresetChange(preset)}
                    size="small"
                  >
                    {preset}
                  </Button>
                </Grid>
              ))}
            </Grid>
            <IndicatorSelector onApply={handleApplyIndicator} />
          </Box>

          <Box flexGrow={1} minHeight={0}>
            <HighchartsReact
              highcharts={Highcharts}
              constructorType={'stockChart'}
              options={chartOptions}
            />
          </Box>
        </Box>
      </Paper>
    </Rnd>
  );
};

export default ChartOverlay;

./src/components/ChartOverlay.tsx

Error: 
  × Expected ',', got '{'
    ╭─[C:\Users\Spider\PycharmProjects\AnalysisWeb\frontend\src\components\ChartOverlay.tsx:76:1]
 76 │       },
 77 │     },
 78 │     title: {
 79 │       text: ${symbol} Price Chart,
    ·              ─
 80 │     },
 81 │     rangeSelector: {
 81 │       selected: 2, // Default to 3M

    ╰────

Caused by:
    Syntax Error