'use client';

import {BarChart, Bar, ReferenceLine} from 'recharts';
import {ChartFrame, chartFurniture} from './ChartFrame';
import {ChartDefs, useHatchIds} from './ChartDefs';
import {useChartMotion} from './useChartMotion';
import {CHART, defaultEncoding} from './palette';
import type {ChartViewProps} from './types';

const TONE = {
  neutral: CHART.reference,
  positive: CHART.positive,
  negative: CHART.negative,
} as const;

/**
 * Bars cannot use a dash pattern, so the third series onward switches to a
 * hatch fill instead — same idea, different channel.
 */
export function BarChartView<T extends object>({
  data,
  xKey,
  series,
  height = 260,
  xFormat,
  yFormat,
  reference,
  isAnimated = true,
  isBare,
  isStacked = false,
}: ChartViewProps<T> & {isStacked?: boolean}) {
  const motion = useChartMotion(isAnimated);
  const hatch = useHatchIds();

  return (
    <ChartFrame height={height}>
      <BarChart data={data} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
        <ChartDefs
          ids={hatch}
          colors={{diagonal: CHART.seriesAt(2), cross: CHART.seriesAt(3)}}
        />
        {chartFurniture({xKey, xFormat, yFormat, isBare})}
        {reference ? (
          <ReferenceLine
            y={reference.y}
            stroke={TONE[reference.tone ?? 'neutral']}
            strokeDasharray="4 4"
            label={{
              value: reference.label,
              position: 'insideTopRight',
              fill: CHART.axis,
              fontSize: 11,
            }}
          />
        ) : null}
        {series.map((s, i) => {
          const encoding = s.encoding ?? (i >= 2 ? 'hatch' : defaultEncoding(i));
          const solid = s.color ?? CHART.seriesAt(i);
          const fill =
            encoding === 'hatch'
              ? `url(#${i === 2 ? hatch.diagonal : hatch.cross})`
              : solid;
          return (
            <Bar
              key={s.key}
              dataKey={s.key}
              name={s.label}
              fill={fill}
              stroke={encoding === 'hatch' ? solid : undefined}
              strokeWidth={encoding === 'hatch' ? 1 : 0}
              stackId={isStacked ? 'stack' : undefined}
              radius={isStacked ? 0 : [3, 3, 0, 0]}
              maxBarSize={48}
              {...motion}
            />
          );
        })}
      </BarChart>
    </ChartFrame>
  );
}
