import { useEffect, useRef } from 'react'
import { createChart, ColorType, IChartApi, ISeriesApi } from 'lightweight-charts'
import { Box, Typography } from '@mui/material'

interface ChartProps {
  data: {
    time: number
    open: number
    high: number
    low: number
    close: number
  }[]
  height?: number
  colors?: {
    backgroundColor?: string
    lineColor?: string
    textColor?: string
    areaTopColor?: string
    areaBottomColor?: string
  }
}

export default function Chart({ data, height = 400, colors }: ChartProps) {
  const chartContainerRef = useRef<HTMLDivElement>(null)
  const chartRef = useRef<IChartApi | null>(null)
  const candlestickSeriesRef = useRef<ISeriesApi<"Candlestick"> | null>(null)

  // Validate data
  if (!data || !Array.isArray(data) || data.length === 0) {
    return (
      <Box sx={{ width: '100%', height, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Typography variant="body2" color="text.secondary">
          No chart data available
        </Typography>
      </Box>
    )
  }

  useEffect(() => {
    if (!chartContainerRef.current) return

    try {
      const handleResize = () => {
        if (chartRef.current && chartContainerRef.current) {
          chartRef.current.applyOptions({ width: chartContainerRef.current.clientWidth })
        }
      }

      const chart = createChart(chartContainerRef.current, {
        layout: {
          background: { type: ColorType.Solid, color: colors?.backgroundColor || '#1E1E1E' },
          textColor: colors?.textColor || '#DDD',
        },
        grid: {
          vertLines: { color: '#333' },
          horzLines: { color: '#333' },
        },
        width: chartContainerRef.current.clientWidth,
        height,
      })

      const candlestickSeries = chart.addCandlestickSeries({
        upColor: '#26a69a',
        downColor: '#ef5350',
        borderVisible: false,
        wickUpColor: '#26a69a',
        wickDownColor: '#ef5350',
      })

      if (data && data.length > 0) {
        candlestickSeries.setData(data as any)
      }

      chartRef.current = chart
      candlestickSeriesRef.current = candlestickSeries

      window.addEventListener('resize', handleResize)

      return () => {
        window.removeEventListener('resize', handleResize)
        chart.remove()
      }
    } catch (error) {
      console.error('Chart initialization error:', error)
    }
  }, [colors, height])

  useEffect(() => {
    if (candlestickSeriesRef.current && data && data.length > 0) {
      try {
        candlestickSeriesRef.current.setData(data as any)
      } catch (error) {
        console.error('Chart data update error:', error)
      }
    }
  }, [data])

  return <Box ref={chartContainerRef} sx={{ width: '100%', height }} />
}
