'use client';

import {LineChart, Line, ReferenceLine} from 'recharts';
import {ChartFrame, chartFurniture} from './ChartFrame';
import {useChartMotion} from './useChartMotion';
import {
  CHART,
  dashFor,
  defaultEncoding,
  strokeWidthFor,
} from './palette';
import type {ChartViewProps} from './types';

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

export function LineChartView<T extends object>({
  data,
  xKey,
  series,
  height = 260,
  xFormat,
  yFormat,
  reference,
  isAnimated = true,
  isBare,
}: ChartViewProps<T>) {
  const motion = useChartMotion(isAnimated);

  return (
    <ChartFrame height={height}>
      <LineChart data={data} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
        {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) => (
          <Line
            key={s.key}
            type="monotone"
            dataKey={s.key}
            name={s.label}
            stroke={s.color ?? CHART.seriesAt(i)}
            strokeWidth={strokeWidthFor(i)}
            strokeDasharray={dashFor(s.encoding ?? defaultEncoding(i))}
            dot={false}
            activeDot={{r: 3}}
            {...motion}
          />
        ))}
      </LineChart>
    </ChartFrame>
  );
}
