import * as React from 'react'
import { cn } from './utils'
import { GaugeChart as GaugeChartImpl } from '../../charts/gauge/index'
import type { GaugeChartConfig, GaugeThreshold } from '../../charts/gauge/types'

export interface GaugeChartProps extends Omit<GaugeChartConfig, 'container'> {
  className?: string
}

function GaugeChart({ className, ...config }: GaugeChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<GaugeChartImpl | null>(null)

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

  React.useEffect(() => {
    if (chartRef.current) {
      chartRef.current.updateConfig(config)
    }
  }, [
    config.value,
    config.min,
    config.max,
    config.label,
    config.unit,
    config.thresholds,
    config.arcWidth,
    config.startAngle,
    config.endAngle,
    config.showValue,
  ])

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

export { GaugeChart }
export type { GaugeThreshold }
