import { useEffect, useRef } from 'react'
import { createChart, IChartApi, ISeriesApi } from 'lightweight-charts'

type Bar = { time: any; open: number; high: number; low: number; close: number }

export default function SimpleKlineChart({ title, data, lastBar }: { title: string; data: Bar[]; lastBar?: Bar }) {
  const containerRef = useRef<HTMLDivElement | null>(null)
  const chartRef = useRef<IChartApi | null>(null)
  const seriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null)

  useEffect(() => {
    if (!containerRef.current) return
    const chart = createChart(containerRef.current, {
      layout: { background: { color: '#0f172a' }, textColor: '#e2e8f0' },
      grid: { vertLines: { color: '#1f2937' }, horzLines: { color: '#1f2937' } },
      rightPriceScale: { borderColor: '#1f2937' },
      timeScale: { borderColor: '#1f2937', timeVisible: true, secondsVisible: false },
      height: 280,
      width: containerRef.current.clientWidth,
    })
    chartRef.current = chart
    const series = chart.addCandlestickSeries({
      upColor: '#16a34a', downColor: '#dc2626', borderUpColor: '#16a34a', borderDownColor: '#dc2626', wickUpColor: '#16a34a', wickDownColor: '#dc2626',
    })
    seriesRef.current = series

    const onResize = () => {
      if (!containerRef.current || !chartRef.current) return
      chartRef.current.applyOptions({ width: containerRef.current.clientWidth })
    }
    window.addEventListener('resize', onResize)
    return () => { window.removeEventListener('resize', onResize); chart.remove() }
  }, [])

  useEffect(() => {
    if (!seriesRef.current) return
    seriesRef.current.setData(data)
  }, [data])

  useEffect(() => {
    if (!seriesRef.current || !lastBar) return
    seriesRef.current.update(lastBar)
  }, [lastBar])

  return (
    <div className="card">
      <div className="title">{title}</div>
      <div ref={containerRef} className="chart" />
    </div>
  )
}
