import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, Modal, ScrollView, Image, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { JournalEvent, TrackingSummary, correctEntryPhotoAnalysis, updateEntry } from '../../../api/tracking';
import { colors, spacing, radii, typography } from '../../../theme';
import { suggestCategory } from '../utils/category';
import { scaleIngredientQuantity, sumIngredientMacros } from '../utils/ingredients';
import { foodEntryPhotoUri } from '../utils/photo';
import { AnalyzingOverlay } from './AnalyzingOverlay';
import { CategoryPickerField } from './CategoryPickerField';
import { IngredientRow } from './IngredientRow';

type Props = {
  visible: boolean;
  entry: JournalEvent | null;
  onClose: () => void;
  onSaved: (summary: TrackingSummary) => void;
};

// Rouvre une entrée déjà journalisée (photo, description texte ou code-barres — jamais
// un "repas" du planning) pour revoir l'analyse complète (photo, ingrédients avec
// calories, macros) et corriger kcal/catégorie/ingrédients avant d'enregistrer — même
// carte que `renderEntryEditor()` côté web (`tracking.js`). Pour les entrées avec photo,
// reprend aussi la correction en langage libre de `PhotoCaptureModal` (`AiResultView`) :
// l'IA revoit la photo déjà stockée à la lumière de la correction, mais rien n'est
// persisté tant que l'utilisateur ne tape pas sur "Enregistrer".
export function EntryDetailModal({ visible, entry, onClose, onSaved }: Props) {
  const [nom, setNom] = useState(entry?.nom ?? '');
  const [ingredients, setIngredients] = useState(entry?.composition ?? []);
  const [kcal, setKcal] = useState(String(Math.round(entry?.kcal ?? 0)));
  const [protein, setProtein] = useState(entry?.protein ?? 0);
  const [carbs, setCarbs] = useState(entry?.carbs ?? 0);
  const [fat, setFat] = useState(entry?.fat ?? 0);
  const [volumeMl, setVolumeMl] = useState(entry?.volumeMl ?? undefined);
  const [category, setCategory] = useState(entry?.trackingCategory ?? suggestCategory());
  const [submitting, setSubmitting] = useState(false);
  const [correcting, setCorrecting] = useState(false);
  const [correctionOpen, setCorrectionOpen] = useState(false);
  const [correction, setCorrection] = useState('');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (visible && entry) {
      setNom(entry.nom);
      setIngredients(entry.composition ?? []);
      setKcal(String(Math.round(entry.kcal)));
      setProtein(entry.protein ?? 0);
      setCarbs(entry.carbs ?? 0);
      setFat(entry.fat ?? 0);
      setVolumeMl(entry.volumeMl ?? undefined);
      setCategory(entry.trackingCategory ?? suggestCategory());
      setCorrectionOpen(false);
      setCorrection('');
      setError(null);
    }
  }, [visible, entry]);

  if (!entry) return null;

  // Resynchronise le total affiché (kcal + macros) avec la nouvelle liste
  // d'ingrédients à chaque modification (quantité changée, ingrédient retiré) — voir
  // `sumIngredientMacros()`. Ne recalcule que si la liste n'est pas vide : un plat
  // sans ingrédient détaillé (ex. après avoir tout retiré) garde son dernier total
  // connu plutôt que de retomber à 0, l'utilisateur pouvant toujours le retaper à la main.
  function applyIngredients(next: typeof ingredients) {
    setIngredients(next);
    if (next.length === 0) return;
    const totals = sumIngredientMacros(next);
    setKcal(String(Math.round(totals.kcal)));
    setProtein(Math.round(totals.protein * 10) / 10);
    setCarbs(Math.round(totals.carbs * 10) / 10);
    setFat(Math.round(totals.fat * 10) / 10);
  }

  function removeIngredient(idx: number) {
    applyIngredients(ingredients.filter((_, i) => i !== idx));
  }

  async function requestCorrection() {
    if (!entry || entry.entryId == null || correction.trim() === '') return;
    setCorrecting(true);
    setError(null);
    try {
      const result = await correctEntryPhotoAnalysis(entry.entryId, ingredients, parseInt(kcal, 10) || entry.kcal, correction.trim());
      setNom(result.nom);
      setIngredients(result.ingredients);
      setKcal(String(result.kcal));
      setProtein(result.protein);
      setCarbs(result.carbs);
      setFat(result.fat);
      setVolumeMl(result.volumeMl ?? undefined);
      setCorrection('');
      setCorrectionOpen(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Correction impossible.');
    } finally {
      setCorrecting(false);
    }
  }

  async function handleSave() {
    if (!entry || entry.entryId == null) return;
    setSubmitting(true);
    setError(null);
    try {
      const summary = await updateEntry(entry.entryId, {
        nom,
        kcal: parseInt(kcal, 10) || entry.kcal,
        protein,
        carbs,
        fat,
        category,
        volumeMl: volumeMl ?? undefined,
        ingredients: ingredients.length > 0 ? ingredients : undefined,
      });
      onSaved(summary);
      onClose();
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Enregistrement impossible.');
      setSubmitting(false);
    }
  }

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen">
      <View style={styles.root}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{entry.photoPath ? 'Revoir la photo' : "Détail de l'entrée"}</Text>
          <Pressable onPress={onClose} hitSlop={12}>
            <Ionicons name="close" size={24} color={colors.text} />
          </Pressable>
        </View>

        {correcting ? (
          <AnalyzingOverlay message="L'IA applique votre correction…" />
        ) : (
          <ScrollView contentContainerStyle={styles.content}>
            {entry.photoPath && <Image source={{ uri: foodEntryPhotoUri(entry.photoPath) }} style={styles.photo} />}
            <Text style={styles.title}>{nom}</Text>

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

            <Text style={styles.label}>Ingrédients identifiés</Text>
            {ingredients.length === 0 && <Text style={styles.bodyText}>Aucun ingrédient</Text>}
            {ingredients.map((ing, idx) => (
              <IngredientRow
                key={`${ing.name}-${idx}`}
                ingredient={ing}
                onChangeQuantity={(quantity) =>
                  applyIngredients(ingredients.map((item, i) => (i === idx ? scaleIngredientQuantity(item, quantity) : item)))
                }
                onRemove={() => removeIngredient(idx)}
              />
            ))}

            {entry.photoPath && (
              <>
                <Pressable style={styles.correctToggle} onPress={() => setCorrectionOpen((v) => !v)}>
                  <Ionicons name="sparkles" size={15} color={colors.primary} />
                  <Text style={styles.correctToggleText}>Corriger l'analyse de l'IA</Text>
                </Pressable>

                {correctionOpen && (
                  <View style={styles.correctionPanel}>
                    <TextInput
                      style={styles.correctionInput}
                      value={correction}
                      onChangeText={setCorrection}
                      placeholder="Ex : ce ne sont pas des champignons mais du maïs"
                      placeholderTextColor={colors.textMuted}
                      multiline
                      autoFocus
                    />
                    <Pressable
                      style={[styles.actionButton, correction.trim() === '' && styles.saveButtonDisabled]}
                      disabled={correction.trim() === ''}
                      onPress={requestCorrection}
                    >
                      <Text style={styles.actionButtonText}>Redemander à l'IA</Text>
                    </Pressable>
                  </View>
                )}
              </>
            )}

            <View style={styles.qtyRow}>
              <Text style={styles.label}>Calories</Text>
              <TextInput style={styles.qtyInput} value={kcal} onChangeText={setKcal} keyboardType="numeric" />
              <Text style={styles.qtyUnit}>kcal</Text>
            </View>

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

            {error && <Text style={styles.errorText}>{error}</Text>}

            <Pressable style={[styles.saveButton, submitting && styles.saveButtonDisabled]} disabled={submitting} onPress={handleSave}>
              {submitting ? <ActivityIndicator color="#fff" /> : <Text style={styles.saveButtonText}>Enregistrer les modifications</Text>}
            </Pressable>
          </ScrollView>
        )}
      </View>
    </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({
  root: { flex: 1, backgroundColor: colors.background },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.sm,
  },
  headerTitle: { ...typography.body, fontWeight: '700', fontSize: 17, color: colors.text },
  content: { padding: spacing.lg, gap: spacing.sm },
  photo: { width: '100%', aspectRatio: 1.4, borderRadius: radii.lg, marginBottom: spacing.xs },
  title: { ...typography.title, fontSize: 20, color: colors.text },
  label: { ...typography.caption, color: colors.textMuted, fontWeight: '700', letterSpacing: 0.3 },
  bodyText: { ...typography.body, fontSize: 14, color: colors.text },
  caption: { ...typography.caption, color: colors.textMuted },
  correctToggle: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'flex-start',
    gap: 6,
    marginTop: spacing.xs,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs + 2,
    borderRadius: radii.pill,
    backgroundColor: colors.primary + '1a',
    borderWidth: 1,
    borderColor: colors.primary,
  },
  correctToggleText: { ...typography.caption, color: colors.primary, fontWeight: '700', fontSize: 13 },
  correctionPanel: { gap: spacing.sm, backgroundColor: colors.card, borderRadius: radii.md, padding: spacing.sm, borderWidth: 1, borderColor: colors.border },
  correctionInput: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
    minHeight: 60,
    textAlignVertical: 'top',
  },
  actionButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingVertical: spacing.sm + 2, alignItems: 'center' },
  actionButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
  qtyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginTop: spacing.xs },
  qtyInput: {
    width: 90,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
  },
  qtyUnit: { ...typography.caption, color: colors.textMuted, marginLeft: 'auto' },
  errorText: { ...typography.body, color: colors.danger, fontSize: 13, marginTop: spacing.xs },
  macrosRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: spacing.sm },
  macro: { alignItems: 'center', gap: 2 },
  macroValue: { ...typography.body, fontWeight: '700', fontSize: 15 },
  saveButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingVertical: spacing.sm + 2, alignItems: 'center', marginTop: spacing.md },
  saveButtonDisabled: { backgroundColor: colors.border },
  saveButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
});
