import Svg, { Defs, LinearGradient as SvgLinearGradient, Stop, Path, Circle, Text as SvgText } from 'react-native-svg';
import { WeightPoint } from '../../../api/weight';
import { colors } from '../../../theme';

// Même géométrie que `wtBuildChart()` (assets/js/weight-tracking.js) — viewBox
// fixe 600×220, marge min/max à 15% (0.3kg mini), pas de librairie de charting
// (cf. cerebrum : réflexe SVG à la main pour un besoin d'une seule courbe).
const CHART_W = 600;
const CHART_H = 220;
const PAD = { top: 16, bottom: 28, left: 8, right: 8 };

// Équivalent `wtPickLabelIndexes()` — 6 graduations max sur l'axe des dates,
// toutes affichées en dessous de 8 points (semaine = 7 jours).
function pickLabelIndexes(count: number): number[] {
  if (count <= 7) return Array.from({ length: count }, (_, i) => i);
  const targetTicks = 6;
  const step = (count - 1) / (targetTicks - 1);
  const indexes = new Set<number>();
  for (let i = 0; i < targetTicks; i++) indexes.add(Math.round(i * step));
  return [...indexes].sort((a, b) => a - b);
}

type Props = {
  points: WeightPoint[];
};

export function WeightChart({ points }: Props) {
  const weights = points.map((p) => p.weight);
  let min = Math.min(...weights);
  let max = Math.max(...weights);
  if (min === max) {
    min -= 1;
    max += 1;
  } else {
    const pad = Math.max((max - min) * 0.15, 0.3);
    min -= pad;
    max += pad;
  }

  const plotW = CHART_W - PAD.left - PAD.right;
  const plotH = CHART_H - PAD.top - PAD.bottom;
  const baseY = PAD.top + plotH;

  const x = (i: number) => (points.length > 1 ? PAD.left + (i / (points.length - 1)) * plotW : PAD.left + plotW / 2);
  const y = (w: number) => PAD.top + (1 - (w - min) / (max - min)) * plotH;

  const coords = points.map((p, i) => [x(i), y(p.weight)] as const);
  const linePath = coords.map(([cx, cy], i) => `${i === 0 ? 'M' : 'L'}${cx},${cy}`).join(' ');
  const areaPath = coords.length > 0 ? `${linePath} L${coords[coords.length - 1][0]},${baseY} L${coords[0][0]},${baseY} Z` : '';

  return (
    <Svg viewBox={`0 0 ${CHART_W} ${CHART_H}`} width="100%" height={CHART_H}>
      <Defs>
        <SvgLinearGradient id="weightAreaGrad" x1="0" y1="0" x2="0" y2="1">
          <Stop offset="0" stopColor={colors.primary} stopOpacity={0.22} />
          <Stop offset="1" stopColor={colors.primary} stopOpacity={0} />
        </SvgLinearGradient>
      </Defs>
      {areaPath !== '' && <Path d={areaPath} fill="url(#weightAreaGrad)" />}
      {linePath !== '' && (
        <Path d={linePath} fill="none" stroke={colors.primary} strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" />
      )}
      {coords.map(([cx, cy], i) => (
        <Circle key={i} cx={cx} cy={cy} r={4} fill={colors.primary} stroke="#fff" strokeWidth={2} />
      ))}
      {pickLabelIndexes(points.length).map((i) => (
        <SvgText key={i} x={x(i)} y={CHART_H - 8} fontSize={10} fontWeight="700" fill={colors.textMuted} textAnchor="middle">
          {points[i].label}
        </SvgText>
      ))}
    </Svg>
  );
}
