import * as React from 'react'
import { cn } from './utils'
import { BarChart as BarChartImpl } from '../../charts/bar/index'
import type { BarChartConfig } from '../../charts/bar/types'
import type { ChartSeries } from '../../charts/types'

export interface BarChartProps extends Omit<BarChartConfig, 'container'> {
  className?: string
}

function BarChart({ className, ...config }: BarChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<BarChartImpl | null>(null)

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

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

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

export { BarChart }
export type { ChartSeries as BarChartSeries }
