import * as React from 'react'
import { cn } from './utils'
import { SparklineChart as SparklineChartImpl } from '../../charts/sparkline/index'
import type { SparklineChartConfig } from '../../charts/sparkline/types'

export interface SparklineChartProps extends Omit<SparklineChartConfig, 'container'> {
  className?: string
}

function SparklineChart({ className, ...config }: SparklineChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<SparklineChartImpl | null>(null)

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

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

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

export { SparklineChart }
