import React from 'react';
import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts';
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  DashboardChartDatum,
} from '../chart';
import { cn } from '../../shared/utils';

export interface BarConfig {
  /** Field name in the data objects */
  dataKey: string;
  /** Fill color. Defaults to `var(--color-{dataKey})` from ChartConfig. */
  fill?: string;
  /** Corner radius of each bar. @default 4 */
  radius?: number;
}

export interface AssistantChartProps {
  data: DashboardChartDatum[];
  config: ChartConfig;
  /** Field used for X axis category labels. @default "month" */
  categoryKey?: string;
  /**
   * Bar definitions. Defaults to one bar per key in `config`.
   * Each bar's fill defaults to `var(--color-{dataKey})`.
   */
  bars?: BarConfig[];
  /** Custom formatter for X axis tick labels. Defaults to first 3 chars of the value. */
  xAxisFormatter?: (value: string) => string;
  className?: string;
}

export function AssistantChart({
  data,
  config,
  categoryKey = 'month',
  bars,
  xAxisFormatter,
  className,
}: AssistantChartProps) {
  const resolvedBars: BarConfig[] = bars ?? Object.keys(config).map(key => ({ dataKey: key }));
  const formatTick = xAxisFormatter ?? ((value: string) => value.slice(0, 3));

  return (
    <ChartContainer config={config} className={cn('min-h-[200px] w-full', className)}>
      <BarChart accessibilityLayer data={data}>
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey={categoryKey}
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          tickFormatter={formatTick}
        />
        <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dashed" />} />
        {resolvedBars.map(bar => (
          <Bar
            key={bar.dataKey}
            dataKey={bar.dataKey}
            fill={bar.fill ?? `var(--color-${bar.dataKey})`}
            radius={bar.radius ?? 4}
          />
        ))}
      </BarChart>
    </ChartContainer>
  );
}
