import * as React from 'react'
import { cn } from './utils'
import { CandlestickChart as CandlestickChartImpl } from '../../charts/candlestick/index'
import type { CandlestickChartConfig, CandlestickItem } from '../../charts/candlestick/types'

export interface CandlestickChartProps extends Omit<CandlestickChartConfig, 'container'> {
  className?: string
}

function CandlestickChart({ className, ...config }: CandlestickChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<CandlestickChartImpl | null>(null)

  React.useEffect(() => {
    if (!containerRef.current) return
    chartRef.current = new CandlestickChartImpl({ ...config, container: containerRef.current })
    return () => {
      chartRef.current?.destroy()
      chartRef.current = null
    }
  }, [])

  React.useEffect(() => {
    if (chartRef.current && config.data) {
      chartRef.current.update(config.data)
    }
  }, [config.data])

  return (
    <div ref={containerRef} data-slot="candlestick-chart" className={cn('w-full', className)} />
  )
}

export { CandlestickChart }
export type { CandlestickItem }
