import { useMemo } from 'react';
import Chart from 'react-apexcharts';

export const DonutChart = ({
  series = [],
  labels = [],
  title = '',
  height = 350,
  colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#06B6D4'],
  showLegend = true,
  donutSize = '70%',
  className = '',
  ...props
}) => {
  const chartOptions = useMemo(() => ({
    chart: {
      type: 'donut',
      height: height,
      toolbar: {
        show: false,
      },
    },
    colors: colors,
    labels: labels,
    legend: {
      show: showLegend,
      position: 'bottom',
    },
    dataLabels: {
      enabled: true,
      formatter: (val) => `${val.toFixed(1)}%`,
    },
    tooltip: {
      theme: 'light',
      y: {
        formatter: (val) => `${val}`,
      },
    },
    plotOptions: {
      pie: {
        donut: {
          size: donutSize,
          labels: {
            show: true,
            name: {
              show: true,
            },
            value: {
              show: true,
              formatter: (val) => `${val}`,
            },
            total: {
              show: true,
              label: 'Total',
              formatter: () => {
                const total = series.reduce((sum, val) => sum + val, 0);
                return total.toString();
              },
            },
          },
        },
      },
    },
  }), [labels, colors, height, showLegend, donutSize, series]);

  return (
    <div className={className}>
      {title && (
        <h3 className="text-lg font-semibold text-gray-900 mb-4">{title}</h3>
      )}
      <Chart
        options={chartOptions}
        series={series}
        type="donut"
        height={height}
        {...props}
      />
    </div>
  );
};

export default DonutChart;

