'use client'

import type { ApexOptions } from 'apexcharts'
import React from 'react'
import { Chart, type ChartProps } from '../Chart'
import { mergeChartOptions } from '../chart.config'

type RadialChartSeries = Array<{
  name: string
  color?: string
  data: number
}>

type RadialChartProps = Pick<
  ChartProps,
  'options' | 'width' | 'height' | 'showLegend'
> & {
  series: RadialChartSeries
  startAngle?: number
  endAngle?: number
  hollow?: string
  tracks?: boolean
}

export const RadialChart = ({
  startAngle = 0,
  endAngle = 360,
  tracks = true,
  options = {},
  hollow,
  series,
  ...props
}: RadialChartProps) => {
  const radialChartOptions: ApexOptions = {
    chart: {
      type: 'radialBar',
    },
    plotOptions: {
      radialBar: {
        startAngle,
        endAngle,
        hollow: {
          size: hollow ?? (series.length > 1 ? '25%' : '65%'),
        },
        track: {
          show: tracks,
          background: 'var(--background-alt)',
          opacity: 1,
          margin: 4,
        },
        dataLabels: {
          show: false,
        },
      },
    },
    stroke: {
      lineCap: 'square',
    },
    legend: {
      position: 'bottom',
      horizontalAlign: 'center',
      fontSize: '12px',
      labels: {
        colors: 'var(--muted-foreground)',
      },
      itemMargin: {
        horizontal: 12,
      },
    },
    states: {
      hover: {
        filter: {
          type: 'none',
        },
      },
      active: {
        filter: {
          type: 'none',
        },
      },
    },
  }

  const colors = series.map((item) => item.color)
  const labels = series.map((item) => item.name)
  const data = series.map((item) => item.data)

  const mergedOptions = React.useMemo(
    () => mergeChartOptions(radialChartOptions, { colors, labels }, options),
    [radialChartOptions, colors, labels, options],
  )

  return (
    <Chart type="radialBar" options={mergedOptions} series={data} {...props} />
  )
}
