import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, Modal, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { AddEntryInput, JournalEvent } from '../../../api/tracking';
import { colors, spacing, radii, typography } from '../../../theme';
import { suggestCategory } from '../utils/category';
import { CategoryPickerField } from './CategoryPickerField';

type Props = {
  visible: boolean;
  entry: JournalEvent | null;
  onClose: () => void;
  onAdd: (input: AddEntryInput) => void;
  submitting: boolean;
};

function parseQuantite(quantite: string | null | undefined) {
  const match = /^([\d]+(?:[.,]\d+)?)\s*(.*)$/.exec(String(quantite ?? '').trim());
  if (!match) return { qty: 1, unit: quantite || 'portion' };
  return { qty: parseFloat(match[1].replace(',', '.')) || 1, unit: match[2] || 'portion' };
}

// Popin "Ajouter à nouveau" — équivalent du bouton refresh `data-tk-requick` de la
// version web (`_timeline.html.twig`/`tracking.js`) : ré-ajoute une entrée déjà
// journalisée (aujourd'hui ou un jour d'historique) comme nouvelle entrée pour
// aujourd'hui, quantité et moment de la journée ajustables, macros recalculées au
// prorata de la quantité d'origine.
export function RequickModal({ visible, entry, onClose, onAdd, submitting }: Props) {
  const base = parseQuantite(entry?.quantite);
  const [qty, setQty] = useState(String(base.qty));
  const [category, setCategory] = useState(suggestCategory());

  useEffect(() => {
    if (visible && entry) {
      setQty(String(parseQuantite(entry.quantite).qty));
      setCategory(suggestCategory());
    }
  }, [visible, entry]);

  if (!entry) return null;

  const parsedQty = parseFloat(qty.replace(',', '.')) || 0;
  const scale = base.qty > 0 ? parsedQty / base.qty : 0;
  const kcal = Math.round((entry.kcal ?? 0) * scale);
  const protein = Math.round((entry.protein ?? 0) * scale * 10) / 10;
  const carbs = Math.round((entry.carbs ?? 0) * scale * 10) / 10;
  const fat = Math.round((entry.fat ?? 0) * scale * 10) / 10;
  const volumeMl = entry.volumeMl ? Math.round(entry.volumeMl * scale) : undefined;

  function handleAdd() {
    onAdd({
      nom: entry!.nom,
      kcal,
      protein,
      carbs,
      fat,
      quantite: `${Number.isInteger(parsedQty) ? parsedQty : parsedQty.toFixed(1)} ${base.unit}`.trim(),
      category,
      volumeMl,
      source: 'rapide',
    });
  }

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
      <Pressable style={styles.scrim} onPress={onClose}>
        <Pressable style={styles.card} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <Ionicons name="refresh" size={18} color={colors.primary} />
            <Text style={styles.title}>Ajouter à nouveau</Text>
            <Pressable onPress={onClose} hitSlop={10}>
              <Ionicons name="close" size={20} color={colors.textMuted} />
            </Pressable>
          </View>

          <Text style={styles.nom}>{entry.nom}</Text>

          <View style={styles.qtyRow}>
            <Text style={styles.label}>Quantité</Text>
            <TextInput style={styles.qtyInput} value={qty} onChangeText={setQty} keyboardType="numeric" />
            <Text style={styles.unit}>{base.unit}</Text>
          </View>

          <CategoryPickerField category={category} onChange={setCategory} />

          <View style={styles.macrosRow}>
            <Macro label="Calories" value={`${kcal} kcal`} color={colors.primary} />
            <Macro label="Protéines" value={`${protein} g`} color="#6366f1" />
            <Macro label="Glucides" value={`${carbs} g`} color="#f59e0b" />
            <Macro label="Lipides" value={`${fat} g`} color="#f43f5e" />
          </View>

          <Pressable style={[styles.addButton, submitting && styles.addButtonDisabled]} disabled={submitting} onPress={handleAdd}>
            {submitting ? <ActivityIndicator color="#fff" /> : <Text style={styles.addButtonText}>Ajouter au suivi</Text>}
          </Pressable>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

function Macro({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <View style={styles.macro}>
      <Text style={[styles.macroValue, { color }]}>{value}</Text>
      <Text style={styles.caption}>{label}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  scrim: { flex: 1, backgroundColor: 'rgba(20,22,45,0.4)', justifyContent: 'center', padding: spacing.lg },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.lg, gap: spacing.sm },
  header: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  title: { ...typography.body, fontWeight: '700', fontSize: 17, color: colors.text, flex: 1 },
  nom: { ...typography.title, fontSize: 18, color: colors.text },
  label: { ...typography.caption, color: colors.textMuted, fontWeight: '700', letterSpacing: 0.3 },
  qtyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  qtyInput: {
    width: 90,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
    marginLeft: 'auto',
  },
  unit: { ...typography.caption, color: colors.textMuted },
  macrosRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: spacing.xs },
  macro: { alignItems: 'center', gap: 2 },
  macroValue: { ...typography.body, fontWeight: '700', fontSize: 15 },
  caption: { ...typography.caption, color: colors.textMuted },
  addButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingVertical: spacing.sm + 2, alignItems: 'center', marginTop: spacing.sm },
  addButtonDisabled: { backgroundColor: colors.border },
  addButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
});
