import * as React from 'react'
import { cn } from './utils'
import { SankeyChart as SankeyChartImpl } from '../../charts/sankey/index'
import type { SankeyChartConfig, SankeyNode, SankeyLink } from '../../charts/sankey/types'

export interface SankeyChartProps extends Omit<SankeyChartConfig, 'container'> {
  className?: string
}

function SankeyChart({ className, ...config }: SankeyChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<SankeyChartImpl | null>(null)

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

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

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

export { SankeyChart }
export type { SankeyNode, SankeyLink }
