import * as React from 'react'
import { cn } from './utils'
import { WaterfallChart as WaterfallChartImpl } from '../../charts/waterfall/index'
import type { WaterfallChartConfig, WaterfallItem } from '../../charts/waterfall/types'

export interface WaterfallChartProps extends Omit<WaterfallChartConfig, 'container'> {
  className?: string
}

function WaterfallChart({ className, ...config }: WaterfallChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<WaterfallChartImpl | null>(null)

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

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

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

export { WaterfallChart }
export type { WaterfallItem }
