import * as React from 'react'
import { cn } from './utils'
import { PieChart as PieChartImpl } from '../../charts/pie/index'
import type { PieChartConfig, PieSlice } from '../../charts/pie/types'

export interface PieChartProps extends Omit<PieChartConfig, 'container'> {
  className?: string
}

function PieChart({ className, ...config }: PieChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<PieChartImpl | null>(null)

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

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

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

export { PieChart }
export type { PieSlice }
