import { useEffect, useState } from 'react';
import { Modal, View, Text, TextInput, Pressable, StyleSheet, ScrollView, ActivityIndicator, Image, Platform } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { AiIngredient, CategoryOption, ItemTypeOption, PickerRecipe, searchRecipes } from '../../../api/mealPlanning';
import { FoodSuggestion, searchFood } from '../../../api/tracking';
import { useAddItem, useGenerateAiIdea } from '../hooks/useMealPlanning';
import { colors, spacing, radii, typography } from '../../../theme';
import { showAlert } from '../../../utils/alert';
import { toSentenceCase } from '../../../utils/text';
import { WEB_URL } from '../../../api/client';

const TYPE_PLACEHOLDER: Record<string, string> = {
  text: "Ex: reste de pâtes, resto avec Julie...",
};

// Mêmes groupes/label que la recherche aliment de Mon suivi (vue "aliment" de
// AddSheet.tsx) — ici on ignore les groupes recette (`mine`/`all`), déjà couverts
// par le step "recipe".
const FOOD_GROUPS: { key: 'ingredients' | 'ciqual'; label: string }[] = [
  { key: 'ingredients', label: 'Mes ingrédients' },
  { key: 'ciqual', label: 'Aliments' },
];

const TYPE_TINT: Record<string, { bg: string; fg: string }> = {
  text: { bg: '#f1f1f3', fg: '#6b6b76' },
  food: { bg: '#e7f7ee', fg: '#2f9e63' },
  recipe: { bg: '#e9f1fe', fg: '#2f80ed' },
  ai: { bg: '#eeecfd', fg: '#5b4fe9' },
};

type Step = 'type' | 'input' | 'food' | 'recipe' | 'ia1' | 'iaResult';

type Props = {
  visible: boolean;
  category: CategoryOption | null;
  itemTypes: ItemTypeOption[];
  onClose: () => void;
  // Jour ciblé (Midi/Soir, grille/liste par semaine) — absent pour Petit-déjeuner/Collation.
  plannedDate?: string | null;
};

export function AddMealModal({ visible, category, itemTypes, onClose, plannedDate }: Props) {
  const [step, setStep] = useState<Step>('type');
  const [type, setType] = useState<string | null>(null);
  const [title, setTitle] = useState('');
  const [recipeQuery, setRecipeQuery] = useState('');
  const [recipeResults, setRecipeResults] = useState<PickerRecipe[]>([]);
  const [searching, setSearching] = useState(false);
  const [foodQuery, setFoodQuery] = useState('');
  const [foodResults, setFoodResults] = useState<{ ingredients: FoodSuggestion[]; ciqual: FoodSuggestion[] } | null>(null);
  const [foodSearching, setFoodSearching] = useState(false);
  const [envie, setEnvie] = useState('');
  const [aiResult, setAiResult] = useState<{ title: string; desc: string | null; ingredients: AiIngredient[] } | null>(null);

  const addItem = useAddItem();
  const generateAiIdea = useGenerateAiIdea();

  useEffect(() => {
    if (!visible) return;
    setStep('type');
    setType(null);
    setTitle('');
    setRecipeQuery('');
    setRecipeResults([]);
    setFoodQuery('');
    setFoodResults(null);
    setEnvie('');
    setAiResult(null);
  }, [visible]);

  useEffect(() => {
    if (step !== 'recipe') return;
    let cancelled = false;
    setSearching(true);
    searchRecipes(recipeQuery.trim())
      .then((res) => { if (!cancelled) setRecipeResults(res.recipes); })
      .finally(() => { if (!cancelled) setSearching(false); });
    return () => { cancelled = true; };
  }, [step, recipeQuery]);

  // Même recherche (endpoint + debounce 250ms) que la vue "aliment" de Mon suivi
  // (AddSheet.tsx) — demande explicite : l'ajout d'un aliment au planning doit
  // passer par la même méthode que l'ajout d'un aliment au suivi.
  useEffect(() => {
    if (step !== 'food') return;
    const query = foodQuery.trim();
    if (query.length < 2) { setFoodResults(null); return; }
    let cancelled = false;
    setFoodSearching(true);
    const timer = setTimeout(() => {
      searchFood(query)
        .then((res) => { if (!cancelled) setFoodResults({ ingredients: res.ingredients, ciqual: res.ciqual }); })
        .catch(() => { if (!cancelled) setFoodResults(null); })
        .finally(() => { if (!cancelled) setFoodSearching(false); });
    }, 250);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [step, foodQuery]);

  function reportError(err: unknown) {
    showAlert('Erreur', err instanceof Error ? err.message : 'Une erreur est survenue.');
  }

  function chooseType(value: string) {
    setType(value);
    setStep(value === 'ai' ? 'ia1' : value === 'recipe' ? 'recipe' : value === 'food' ? 'food' : 'input');
  }

  function submitAndClose(input: { title: string; subtitle?: string; recipeId?: number; ingredients?: AiIngredient[] }) {
    if (!category || !type) return;
    addItem.mutate(
      { category: category.value, type, ...(plannedDate ? { plannedDate } : {}), ...input },
      { onError: reportError, onSuccess: onClose },
    );
  }

  function generate() {
    generateAiIdea.mutate(
      { ingredients: '', envie, assumeBasics: true },
      { onError: reportError, onSuccess: (result) => { setAiResult(result); setStep('iaResult'); } },
    );
  }

  if (!category) return null;

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <ScrollView keyboardShouldPersistTaps="handled">
            <View style={styles.header}>
              <View style={{ flex: 1 }}>
                <Text style={styles.title}>Nouveau repas</Text>
                {step !== 'type' ? (
                  <View style={styles.chip}>
                    <View style={[styles.chipDot, { backgroundColor: category.gradient[1] }]} />
                    <Text style={styles.chipText}>{category.label}</Text>
                  </View>
                ) : null}
              </View>
              <Pressable onPress={onClose} hitSlop={8} style={styles.closeBtn}>
                <Ionicons name="close" size={16} color={colors.textMuted} />
              </Pressable>
            </View>

            {step === 'type' ? (
              <View style={styles.typeGrid}>
                {itemTypes.map((t) => {
                  const tint = TYPE_TINT[t.value] ?? TYPE_TINT.text;
                  return (
                    <Pressable key={t.value} style={styles.typeOpt} onPress={() => chooseType(t.value)}>
                      <View style={[styles.typeBadge, { backgroundColor: tint.bg }]}>
                        <Text style={[styles.typeBadgeText, { color: tint.fg }]}>{t.badge}</Text>
                      </View>
                      <Text style={styles.typeLabel}>{t.label}</Text>
                    </Pressable>
                  );
                })}
              </View>
            ) : null}

            {step === 'input' && type ? (
              <View style={styles.stepGap}>
                <TextInput
                  style={styles.input}
                  value={title}
                  onChangeText={setTitle}
                  placeholder={TYPE_PLACEHOLDER[type] ?? ''}
                  placeholderTextColor={colors.textMuted}
                  autoFocus
                />
                <View style={styles.actions}>
                  <Pressable style={styles.ghostBtn} onPress={() => setStep('type')}>
                    <Text style={styles.ghostBtnText}>Retour</Text>
                  </Pressable>
                  <Pressable
                    style={[styles.primaryBtn, (title.trim() === '' || addItem.isPending) && styles.primaryBtnDisabled]}
                    disabled={title.trim() === '' || addItem.isPending}
                    onPress={() => submitAndClose({ title: title.trim() })}
                  >
                    <Text style={styles.primaryBtnText}>Ajouter</Text>
                  </Pressable>
                </View>
              </View>
            ) : null}

            {step === 'recipe' ? (
              <View style={styles.stepGap}>
                <TextInput
                  style={styles.input}
                  value={recipeQuery}
                  onChangeText={setRecipeQuery}
                  placeholder="Rechercher une recette…"
                  placeholderTextColor={colors.textMuted}
                  autoCapitalize="none"
                />
                {searching ? (
                  <ActivityIndicator color={colors.primary} />
                ) : (
                  <View style={styles.recipeList}>
                    {recipeResults.length === 0 ? (
                      <Text style={styles.hint}>Aucune recette trouvée</Text>
                    ) : (
                      recipeResults.map((recipe) => {
                        const imageUri = recipe.imageUrl
                          ? Platform.OS === 'web' ? recipe.imageUrl : `${WEB_URL}${recipe.imageUrl}`
                          : null;
                        return (
                          <Pressable
                            key={recipe.id}
                            style={styles.recipeRow}
                            disabled={addItem.isPending}
                            onPress={() => submitAndClose({ title: recipe.name, recipeId: recipe.id })}
                          >
                            <View style={styles.recipeThumb}>
                              {imageUri ? (
                                <Image source={{ uri: imageUri }} style={styles.recipeThumbImage} />
                              ) : (
                                <Ionicons name="restaurant-outline" size={16} color={colors.textMuted} />
                              )}
                            </View>
                            <Text style={styles.recipeRowText}>{toSentenceCase(recipe.name)}</Text>
                          </Pressable>
                        );
                      })
                    )}
                  </View>
                )}
                <View style={styles.actions}>
                  <Pressable style={styles.ghostBtn} onPress={() => setStep('type')}>
                    <Text style={styles.ghostBtnText}>Retour</Text>
                  </Pressable>
                </View>
              </View>
            ) : null}

            {step === 'food' ? (
              <View style={styles.stepGap}>
                <TextInput
                  style={styles.input}
                  value={foodQuery}
                  onChangeText={setFoodQuery}
                  placeholder="Rechercher un aliment…"
                  placeholderTextColor={colors.textMuted}
                  autoCapitalize="none"
                  autoFocus
                />
                {foodSearching ? (
                  <ActivityIndicator color={colors.primary} />
                ) : (
                  <View style={styles.recipeList}>
                    {foodQuery.trim().length < 2 ? (
                      <Text style={styles.hint}>Tapez au moins 2 lettres…</Text>
                    ) : !foodResults || FOOD_GROUPS.every((g) => foodResults[g.key].length === 0) ? (
                      <Text style={styles.hint}>Aucun résultat</Text>
                    ) : (
                      FOOD_GROUPS.map((group) => {
                        const items = foodResults[group.key];
                        if (items.length === 0) return null;
                        return (
                          <View key={group.key}>
                            <Text style={styles.fieldLabel}>{group.label}</Text>
                            {items.map((item, idx) => (
                              <Pressable
                                key={`${group.key}-${idx}`}
                                style={styles.recipeRow}
                                disabled={addItem.isPending}
                                onPress={() => submitAndClose({ title: item.nom })}
                              >
                                <Text style={styles.recipeRowText}>{item.nom}</Text>
                                <Text style={styles.foodRowSub}>
                                  {item.portionLabel} · {item.caloriesPer100} kcal/100g
                                </Text>
                              </Pressable>
                            ))}
                          </View>
                        );
                      })
                    )}
                  </View>
                )}
                <View style={styles.actions}>
                  <Pressable style={styles.ghostBtn} onPress={() => setStep('type')}>
                    <Text style={styles.ghostBtnText}>Retour</Text>
                  </Pressable>
                </View>
              </View>
            ) : null}

            {step === 'ia1' ? (
              <View style={styles.stepGap}>
                <Text style={styles.hint}>Demandez à <Text style={{ fontWeight: '700', color: colors.text }}>CLEM AI</Text> d'inventer une idée de repas.</Text>
                <Text style={styles.fieldLabel}>Envie de...</Text>
                <TextInput
                  style={styles.input}
                  value={envie}
                  onChangeText={setEnvie}
                  placeholder="Ex: Poulet et haricots verts"
                  placeholderTextColor={colors.textMuted}
                />
                <View style={styles.actions}>
                  <Pressable style={styles.ghostBtn} onPress={() => setStep('type')}>
                    <Text style={styles.ghostBtnText}>Retour</Text>
                  </Pressable>
                  <Pressable
                    style={[styles.primaryBtn, generateAiIdea.isPending && styles.primaryBtnDisabled]}
                    disabled={generateAiIdea.isPending}
                    onPress={generate}
                  >
                    {generateAiIdea.isPending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryBtnText}>Générer</Text>}
                  </Pressable>
                </View>
              </View>
            ) : null}

            {step === 'iaResult' && aiResult ? (
              <View style={styles.stepGap}>
                <View style={styles.iaResult}>
                  <View style={[styles.typeBadge, { backgroundColor: TYPE_TINT.ai.bg }]}>
                    <Text style={[styles.typeBadgeText, { color: TYPE_TINT.ai.fg }]}>IA</Text>
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.iaResultTitle}>{aiResult.title}</Text>
                    {aiResult.desc ? <Text style={styles.iaResultDesc}>{aiResult.desc}</Text> : null}
                  </View>
                </View>
                {aiResult.ingredients.length > 0 ? (
                  <View>
                    <Text style={styles.fieldLabel}>Sera ajouté à la liste de courses</Text>
                    <Text style={styles.hint}>
                      {aiResult.ingredients.map((i) => `${i.name} (${i.quantity} ${i.unit})`).join(' · ')}
                    </Text>
                  </View>
                ) : null}
                <View style={styles.actions}>
                  <Pressable style={styles.ghostBtn} disabled={generateAiIdea.isPending} onPress={generate}>
                    <Text style={styles.ghostBtnText}>Régénérer</Text>
                  </Pressable>
                  <Pressable
                    style={[styles.primaryBtn, addItem.isPending && styles.primaryBtnDisabled]}
                    disabled={addItem.isPending}
                    onPress={() => submitAndClose({ title: aiResult.title, subtitle: aiResult.desc ?? undefined, ingredients: aiResult.ingredients })}
                  >
                    <Text style={styles.primaryBtnText}>Utiliser cette recette</Text>
                  </Pressable>
                </View>
              </View>
            ) : null}
          </ScrollView>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: { flex: 1, backgroundColor: 'rgba(20, 20, 26, 0.4)', justifyContent: 'flex-end' },
  sheet: { backgroundColor: colors.card, borderTopLeftRadius: radii.xl, borderTopRightRadius: radii.xl, padding: spacing.lg, maxHeight: '86%' },
  header: { flexDirection: 'row', alignItems: 'flex-start', marginBottom: spacing.md },
  title: { ...typography.title, fontSize: 18, color: colors.text },
  chip: { flexDirection: 'row', alignItems: 'center', gap: 6, marginTop: 6, alignSelf: 'flex-start', backgroundColor: colors.background, paddingVertical: 4, paddingHorizontal: 10, borderRadius: radii.pill },
  chipDot: { width: 6, height: 6, borderRadius: 3 },
  chipText: { ...typography.caption, fontSize: 11, fontWeight: '700', color: colors.textMuted },
  closeBtn: { width: 30, height: 30, borderRadius: radii.pill, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' },
  typeGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  typeOpt: { width: '47%', flexDirection: 'row', alignItems: 'center', gap: spacing.sm, padding: spacing.sm + 4, borderRadius: radii.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.background },
  typeBadge: { width: 28, height: 28, borderRadius: 9, alignItems: 'center', justifyContent: 'center' },
  typeBadgeText: { fontSize: 10.5, fontWeight: '800' },
  typeLabel: { ...typography.body, fontSize: 12.5, fontWeight: '600', color: colors.text, flexShrink: 1 },
  stepGap: { gap: spacing.sm },
  input: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: spacing.sm, paddingVertical: spacing.sm + 2, color: colors.text, backgroundColor: colors.background },
  fieldLabel: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.textMuted },
  actions: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.xs },
  ghostBtn: { paddingVertical: spacing.sm + 2, paddingHorizontal: spacing.md, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border, alignItems: 'center', justifyContent: 'center' },
  ghostBtnText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.textMuted },
  primaryBtn: { flex: 1, paddingVertical: spacing.sm + 2, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  primaryBtnDisabled: { opacity: 0.5 },
  primaryBtnText: { color: '#fff', fontWeight: '700', fontSize: 14 },
  recipeList: { gap: 6, maxHeight: 280 },
  recipeRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingVertical: 8, paddingHorizontal: spacing.sm, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border },
  recipeThumb: { width: 34, height: 34, borderRadius: radii.sm, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center', overflow: 'hidden' },
  recipeThumbImage: { width: '100%', height: '100%' },
  recipeRowText: { ...typography.body, fontSize: 13.5, fontWeight: '600', color: colors.text, flexShrink: 1 },
  foodRowSub: { ...typography.caption, fontSize: 11.5, color: colors.textMuted, marginTop: 2 },
  hint: { ...typography.caption, color: colors.textMuted, paddingVertical: spacing.sm },
  iaResult: { flexDirection: 'row', gap: spacing.sm, backgroundColor: '#f7f6ff', borderWidth: 1, borderColor: '#eeecfd', borderRadius: radii.md, padding: spacing.sm + 4 },
  iaResultTitle: { ...typography.body, fontSize: 15, fontWeight: '700', color: colors.text },
  iaResultDesc: { ...typography.caption, fontSize: 12.5, color: colors.textMuted, marginTop: 3 },
});
