import { useMemo } from 'react';
import { BaseChart } from '../BaseChart';
import type { EChartsOption } from 'echarts';
import { chartSeriesColors } from '@lib/theme';

interface Series {
  key: string;
  name: string;
  color?: string;
}

interface BarChartProps {
  data: Record<string, unknown>[];
  xKey: string;
  series: Series[];
  height?: number;
  className?: string;
  horizontal?: boolean;
  /** 각 데이터 항목별 개별 색상 배열 (단일 시리즈에서 Cell 대체) */
  itemColors?: string[];
}

export function BarChart({ data, xKey, series, height = 200, className, horizontal, itemColors }: BarChartProps) {
  const option = useMemo<EChartsOption>(() => {
    const categoryData = data.map(d => d[xKey] as string);
    const xAxisConfig = horizontal
      ? { type: 'value' as const }
      : { type: 'category' as const, data: categoryData };
    const yAxisConfig = horizontal
      ? { type: 'category' as const, data: categoryData }
      : { type: 'value' as const };

    return {
      grid: { top: 10, right: 10, bottom: 24, left: horizontal ? 60 : 36, containLabel: false },
      tooltip: { trigger: 'axis' },
      xAxis: xAxisConfig,
      yAxis: yAxisConfig,
      series: series.map((s, i) => ({
        name: s.name,
        type: 'bar',
        data: itemColors && series.length === 1
          ? data.map((d, j) => ({
              value: d[s.key] as number,
              itemStyle: { color: itemColors[j] ?? chartSeriesColors[i % chartSeriesColors.length] },
            }))
          : data.map(d => d[s.key] as number),
        itemStyle: { color: s.color ?? chartSeriesColors[i % chartSeriesColors.length], borderRadius: 2 },
      })),
    };
  }, [data, xKey, series, horizontal, itemColors]);

  return <BaseChart option={option} height={height} className={className} />;
}
