import Svg, { Rect, Text as SvgText } from 'react-native-svg';
import { ActivityPoint } from '../../../api/activity';
import { colors } from '../../../theme';

// Barres (durée/jour) plutôt que la ligne de `WeightChart` — une activité est un
// total ponctuel par jour, pas une valeur qui évolue continûment (cf. cerebrum :
// réflexe SVG à la main pour un besoin d'un seul graphique, pas de librairie).
const CHART_W = 600;
const CHART_H = 220;
const PAD = { top: 16, bottom: 28, left: 8, right: 8 };

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: ActivityPoint[];
};

export function ActivityChart({ points }: Props) {
  const max = Math.max(...points.map((p) => p.durationMinutes), 1);

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

  const slot = points.length > 0 ? plotW / points.length : plotW;
  const barW = Math.min(slot * 0.55, 28);

  return (
    <Svg viewBox={`0 0 ${CHART_W} ${CHART_H}`} width="100%" height={CHART_H}>
      {points.map((p, i) => {
        const cx = PAD.left + slot * (i + 0.5);
        const h = p.durationMinutes > 0 ? Math.max((p.durationMinutes / max) * plotH, 3) : 0;
        return (
          <Rect
            key={p.date}
            x={cx - barW / 2}
            y={baseY - h}
            width={barW}
            height={h}
            rx={4}
            fill={colors.primary}
            opacity={p.durationMinutes > 0 ? 1 : 0.15}
          />
        );
      })}
      {pickLabelIndexes(points.length).map((i) => (
        <SvgText
          key={i}
          x={PAD.left + slot * (i + 0.5)}
          y={CHART_H - 8}
          fontSize={10}
          fontWeight="700"
          fill={colors.textMuted}
          textAnchor="middle"
        >
          {points[i].label}
        </SvgText>
      ))}
    </Svg>
  );
}
