'use client'

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

type BarChartProps = Omit<ChartProps, 'type'> & {
  horizontal?: boolean
  columnWidth?: string
  stacked?: boolean
}

export const BarChart = ({
  horizontal = false,
  columnWidth = '70%',
  stacked = false,
  options = {},
  series,
  ...props
}: BarChartProps) => {
  const barChartOptions = React.useMemo<ApexOptions>(
    () => ({
      chart: { type: 'bar', stacked },
      plotOptions: {
        bar: {
          horizontal,
          columnWidth,
          borderRadius: series.length > 1 ? 2 : 4,
          borderRadiusApplication: 'end',
          borderRadiusWhenStacked: 'last',
        },
      },
      // https://github.com/apexcharts/apexcharts.js/issues/1350#issuecomment-721688950
      ...(series.length > 1 &&
        !stacked && {
          stroke: { colors: ['transparent'], width: 4 },
        }),
      fill: { opacity: 1 },
      xaxis: {
        axisBorder: { offsetY: series.length > 1 ? 0 : 0.5 },
        crosshairs: { show: false },
      },
      states: {
        hover: { filter: { type: 'none' } },
        active: { filter: { type: 'none' } },
      },
      tooltip: {
        shared: true,
        intersect: false,
      },
    }),
    [stacked, horizontal, columnWidth, series.length],
  )

  const mergedOptions = React.useMemo(
    () => mergeChartOptions(barChartOptions, options),
    [barChartOptions, options],
  )

  return <Chart type="bar" options={mergedOptions} series={series} {...props} />
}
