import { View, Text, StyleSheet } from 'react-native';
import Svg, { Rect, Line } from 'react-native-svg';
import Ionicons from '@expo/vector-icons/Ionicons';
import { colors, spacing, radii, typography } from '../../../theme';
import { CircularProgress } from './CircularProgress';
import { DieticianReference, DieticianReferenceType } from '../../../api/dieticianReport';

// Couleurs par type de référence, reprises du mockup Claude Design "ClemIA Chatbot" —
// distinctes de `colors.primary` (violet du reste de l'app) pour que chaque type de
// carte reste visuellement identifiable au premier coup d'œil dans le fil de chat.
// Exporté : réutilisé par ClemIAScreen.tsx pour le badge de type posé sur CHAQUE message
// de l'historique unifié (pas seulement ceux avec une carte graphique complète ici).
export const TYPE_STYLE: Record<DieticianReferenceType, { color: string; light: string; bg: string; border: string; icon: keyof typeof Ionicons.glyphMap }> = {
  repas: { color: '#4F39F6', light: '#c4bcff', bg: '#f4f1ff', border: '#ddd6ff', icon: 'restaurant-outline' },
  bilan: { color: '#0E9C96', light: '#a8e2df', bg: '#effbfa', border: '#c9eeeb', icon: 'stats-chart-outline' },
  sport: { color: '#E4701E', light: '#f9cfa9', bg: '#fff6ef', border: '#fddcc2', icon: 'walk-outline' },
  hydratation: { color: '#0C87C4', light: '#c7e6f8', bg: '#eff8fd', border: '#c7e6f8', icon: 'water-outline' },
  // Pas encore de carte graphique associée (voir DieticianReportService::buildReferenceSnapshot()) —
  // sert seulement au badge de type du message dans l'historique.
  recette: { color: '#C0269B', light: '#f0b8e3', bg: '#fdf1fa', border: '#f3d3ec', icon: 'book-outline' },
};

// Date d'une séance précise (carte 'sport' ciblée, voir plus bas) — format "22 août",
// pas de "Aujourd'hui/Hier" ici (contrairement à `dayLabel()` de ClemIAScreen.tsx) : la
// récence est déjà portée par la pastille de type au-dessus, cette carte est un simple
// détail figé une fois envoyée.
function formatActivityDate(iso: string): string {
  return new Date(`${iso}T00:00:00`).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long' });
}

// Badge affiché au-dessus de la bulle utilisateur ("🍽 Déjeuner · 12:40") — voir mockup.
export function ReferencePill({ reference }: { reference: DieticianReference }) {
  const style = TYPE_STYLE[reference.type];
  return (
    <View style={[pillStyles.pill, { backgroundColor: style.bg, borderColor: style.border }]}>
      <Ionicons name={style.icon} size={12} color={style.color} />
      <Text style={[pillStyles.text, { color: style.color }]}>{reference.label}</Text>
    </View>
  );
}

const pillStyles = StyleSheet.create({
  pill: {
    // Toujours posé au-dessus d'une bulle utilisateur (voir ClemIAScreen.tsx) —
    // aligné à gauche comme elle (demande explicite utilisateur : utilisateur à
    // gauche, ClemIA à droite).
    alignSelf: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    borderWidth: 1,
    borderRadius: radii.pill,
    paddingVertical: 5,
    paddingHorizontal: 10,
  },
  text: { fontSize: 12, fontWeight: '700' },
});

function WeekBarChart({
  values,
  highlight,
  color,
  lightColor,
  targetRatio,
}: {
  values: number[];
  highlight: boolean[];
  color: string;
  lightColor: string;
  targetRatio?: number;
}) {
  const W = 320;
  const H = 100;
  const pad = { top: 4, bottom: 16 };
  const plotH = H - pad.top - pad.bottom;
  const max = Math.max(...values, 1, targetRatio ? targetRatio : 0);
  const slot = W / values.length;
  const barW = Math.min(slot * 0.55, 26);

  return (
    <Svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H}>
      {targetRatio !== undefined && (
        <Line
          x1={0}
          x2={W}
          y1={pad.top + plotH - (targetRatio / max) * plotH}
          y2={pad.top + plotH - (targetRatio / max) * plotH}
          stroke={colors.border}
          strokeWidth={1}
          strokeDasharray="4,3"
        />
      )}
      {values.map((v, i) => {
        const h = v > 0 ? Math.max((v / max) * plotH, 2) : 0;
        const cx = slot * (i + 0.5);
        return (
          <Rect
            key={i}
            x={cx - barW / 2}
            y={pad.top + plotH - h}
            width={barW}
            height={h}
            rx={4}
            fill={highlight[i] ? color : lightColor}
          />
        );
      })}
    </Svg>
  );
}

function WeekLabels({ labels }: { labels: string[] }) {
  return (
    <View style={styles.weekLabels}>
      {labels.map((label, i) => (
        <Text key={i} style={styles.weekLabel}>
          {label}
        </Text>
      ))}
    </View>
  );
}

function MacroBar({ label, grams, ratio, color }: { label: string; grams: number; ratio: number; color: string }) {
  return (
    <View style={styles.macroRow}>
      <Text style={styles.macroLabel}>{label}</Text>
      <View style={styles.macroTrack}>
        <View style={[styles.macroFill, { width: `${Math.max(4, Math.round(ratio * 100))}%`, backgroundColor: color }]} />
      </View>
      <Text style={styles.macroValue}>{Math.round(grams)} g</Text>
    </View>
  );
}

function StatTile({ value, label }: { value: string; label: string }) {
  return (
    <View style={styles.statTile}>
      <Text style={styles.statValue}>{value}</Text>
      <Text style={styles.statLabel}>{label}</Text>
    </View>
  );
}

// Carte graphique affichée sous la bulle de réponse de ClemIA — un rendu par type de
// référence, données déjà figées au moment de l'envoi (`reference.data`, voir
// `DieticianReportService::buildReferenceSnapshot()`), jamais recalculées ici.
export function ChatReferenceCard({ reference }: { reference: DieticianReference }) {
  const style = TYPE_STYLE[reference.type];

  if (reference.type === 'repas') {
    const d = reference.data as { nom: string; kcal: number; protein: number; carbs: number; fat: number };
    const maxMacro = Math.max(d.protein, d.carbs, d.fat, 1);
    return (
      <View style={[styles.card, { borderColor: style.border }]}>
        <View style={styles.cardHeaderRow}>
          <Text style={styles.cardTitle}>{d.nom}</Text>
          <Text style={styles.cardMeta}>{d.kcal} kcal</Text>
        </View>
        <View style={styles.macros}>
          <MacroBar label="Protéines" grams={d.protein} ratio={d.protein / maxMacro} color={style.color} />
          <MacroBar label="Glucides" grams={d.carbs} ratio={d.carbs / maxMacro} color={style.color} />
          <MacroBar label="Lipides" grams={d.fat} ratio={d.fat / maxMacro} color={style.color} />
        </View>
      </View>
    );
  }

  if (reference.type === 'bilan') {
    const d = reference.data as {
      days: { label: string; kcal: number; overTarget: boolean }[];
      target: number | null;
      avgKcal: number;
      weightDeltaKg: number | null;
    };
    return (
      <View style={[styles.card, { borderColor: style.border }]}>
        <View style={styles.cardHeaderRow}>
          <Text style={styles.cardTitle}>Apport quotidien</Text>
          <Text style={styles.cardMeta}>{d.target !== null ? `obj. ${d.target} kcal` : 'objectif non renseigné'}</Text>
        </View>
        <WeekBarChart
          values={d.days.map((day) => day.kcal)}
          highlight={d.days.map((day) => day.overTarget)}
          color={style.color}
          lightColor={style.light}
          targetRatio={d.target ?? undefined}
        />
        <WeekLabels labels={d.days.map((day) => day.label)} />
        <View style={styles.statsRow}>
          <StatTile value={String(d.avgKcal)} label="Moyenne / jour" />
          <StatTile value={d.weightDeltaKg !== null ? `${d.weightDeltaKg > 0 ? '+' : ''}${d.weightDeltaKg} kg` : '—'} label="Poids semaine" />
        </View>
      </View>
    );
  }

  // 'sport' a deux formes possibles selon que le picker "Activité" a ciblé une séance
  // précise ou non (voir DieticianReportService::buildReferenceSnapshot()) — la forme
  // agrégat 7 jours (`days`) n'est plus posée par le picker mais reste possible pour
  // d'anciens messages persistés / questions libres sans sélection.
  if (reference.type === 'sport' && 'description' in reference.data) {
    const d = reference.data as { description: string; durationMinutes: number | null; recordedAt: string };
    return (
      <View style={[styles.card, { borderColor: style.border }]}>
        <View style={styles.cardHeaderRow}>
          <Text style={styles.cardTitle}>{d.description}</Text>
          <Text style={styles.cardMeta}>{d.durationMinutes !== null ? `${d.durationMinutes} min` : 'Durée non renseignée'}</Text>
        </View>
        <Text style={styles.todayText}>{formatActivityDate(d.recordedAt)}</Text>
      </View>
    );
  }

  if (reference.type === 'sport') {
    const d = reference.data as {
      days: { label: string; minutes: number }[];
      totalMinutes: number;
      activeDays: number;
      todayDescription: string | null;
    };
    return (
      <View style={[styles.card, { borderColor: style.border }]}>
        <View style={styles.cardHeaderRow}>
          <Text style={styles.cardTitle}>Activité (7 jours)</Text>
          <Text style={styles.cardMeta}>{d.totalMinutes} min · {d.activeDays} j actifs</Text>
        </View>
        <WeekBarChart
          values={d.days.map((day) => day.minutes)}
          highlight={d.days.map((day) => day.minutes > 0)}
          color={style.color}
          lightColor={style.light}
        />
        <WeekLabels labels={d.days.map((day) => day.label)} />
        <Text style={styles.todayText}>{d.todayDescription ?? "Pas d'activité enregistrée aujourd'hui."}</Text>
      </View>
    );
  }

  // hydratation
  const d = reference.data as {
    currentMl: number;
    targetMl: number | null;
    percent: number;
    glasses: { filled: number; total: number };
  };
  return (
    <View style={[styles.card, { borderColor: style.border }]}>
      <View style={styles.hydraRow}>
        <CircularProgress size={72} strokeWidth={8} progress={d.percent} color={style.color} trackColor={style.bg}>
          <Text style={styles.hydraPercent}>{d.percent}%</Text>
          <Text style={styles.hydraPercentLabel}>objectif</Text>
        </CircularProgress>
        <View style={styles.hydraDetails}>
          <Text style={styles.cardTitle}>
            {(d.currentMl / 1000).toFixed(2).replace('.', ',')} L{d.targetMl !== null ? ` sur ${(d.targetMl / 1000).toFixed(1).replace('.', ',')} L` : ''}
          </Text>
          <View style={styles.glassesRow}>
            {Array.from({ length: d.glasses.total }, (_, i) => (
              <View key={i} style={[styles.glass, { backgroundColor: i < d.glasses.filled ? style.color : style.bg }]} />
            ))}
          </View>
          <Text style={styles.cardMeta}>
            {d.glasses.filled} verre{d.glasses.filled > 1 ? 's' : ''} sur {d.glasses.total}
          </Text>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    // Largeur fixe (pas de `%`) : le composant est imbriqué dans une colonne de bulle
    // qui ne s'étire pas (`alignItems: 'flex-start'/'flex-end'`), donc un enfant en
    // `width: '100%'` (le SVG des graphiques ci-dessous, les barres de macros) n'aurait
    // sinon aucune largeur de référence pour se résoudre.
    width: 260,
    borderWidth: 1,
    borderRadius: radii.lg,
    padding: spacing.md,
    gap: spacing.sm,
    backgroundColor: colors.card,
  },
  cardHeaderRow: { flexDirection: 'row', alignItems: 'baseline', justifyContent: 'space-between', gap: spacing.sm },
  cardTitle: { ...typography.body, fontSize: 14.5, fontWeight: '700', color: colors.text },
  cardMeta: { fontSize: 12, color: colors.textMuted },
  macros: { gap: 8 },
  macroRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  macroLabel: { width: 66, fontSize: 11.5, color: colors.textMuted },
  macroTrack: { flex: 1, height: 8, borderRadius: radii.pill, backgroundColor: colors.surface, overflow: 'hidden' },
  macroFill: { height: '100%', borderRadius: radii.pill },
  macroValue: { width: 40, textAlign: 'right', fontSize: 11.5, fontWeight: '700', color: colors.text },
  weekLabels: { flexDirection: 'row' },
  weekLabel: { flex: 1, textAlign: 'center', fontSize: 10, color: colors.textMuted },
  statsRow: { flexDirection: 'row', gap: 8 },
  statTile: { flex: 1, backgroundColor: colors.surface, borderRadius: radii.sm + 2, padding: 8 },
  statValue: { fontSize: 15, fontWeight: '700', color: colors.text },
  statLabel: { fontSize: 11, color: colors.textMuted },
  todayText: { fontSize: 13, color: colors.text, lineHeight: 18 },
  hydraRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md },
  hydraPercent: { fontSize: 15, fontWeight: '800', color: colors.text },
  hydraPercentLabel: { fontSize: 9.5, color: colors.textMuted },
  hydraDetails: { flex: 1, gap: 8 },
  glassesRow: { flexDirection: 'row', gap: 5 },
  glass: { width: 12, height: 24, borderRadius: 3 },
});
