import { useEffect, useState } from 'react';
import { Modal, View, Text, Pressable, StyleSheet, ScrollView, ActivityIndicator, Image, Platform, TextInput } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { CategoryOption, AutofillPreviewItem } from '../../../api/mealPlanning';
import { usePreviewAutofill, useApplyAutofill, useResuggestAutofillItem } from '../hooks/useMealPlanning';
import { addDaysIso, dayInfo, diffDaysIso, saturdayOnOrAfterIso, todayIso } from '../utils/weekDates';
import { colors, spacing, radii, typography } from '../../../theme';
import { WEB_URL } from '../../../api/client';
import { showAlert } from '../../../utils/alert';
import { savePendingAutofillResume } from '../pendingAutofillResume';
import { SOURCE_LABEL, SOURCE_TINT } from '../utils/mealSource';

// Même route que RecipeCatalogScreen.tsx (IMPORT_PATH).
const RECIPE_IMPORT_PATH = '/import/recette';

// Plage maximale proposable — même borne que le clamp serveur (MealPlanController::autofill-preview).
const MAX_DAYS = 60;

// Même convention que RecipeCard.tsx/foodEntryPhotoUri() pour une URL d'image relative
// renvoyée par Symfony : chemin relatif tel quel sur web (même origine), préfixé par
// WEB_URL sur natif (bundle mobile sur un hôte distinct).
function imageUri(imageUrl: string | null): string | null {
  if (!imageUrl) return null;
  return Platform.OS === 'web' ? imageUrl : `${WEB_URL}${imageUrl}`;
}

type Step = 'dates' | 'review';

type Props = {
  visible: boolean;
  onClose: () => void;
  // Pour libellé/couleur des propositions à l'étape de revue — même source que le reste
  // de l'écran (data.meta.categories, voir MealPlanningScreen.tsx).
  categories: CategoryOption[];
  // Retour depuis la création d'une recette IA (bouton "Créer une recette IA" d'une
  // proposition) — voir pendingAutofillResume.ts/MealPlanningScreen.tsx. Quand fourni,
  // rouvre directement l'étape de revue avec cette liste au lieu de repartir de "dates".
  resumeItems?: AutofillPreviewItem[] | null;
};

// Bouton "Remplir automatiquement" (MealPlanningScreen.tsx) : en 2 étapes — 1) période à
// remplir (par défaut le prochain samedi, une semaine, modifiable), 2) popin de revue des
// recettes proposées par MealPlanAutofillService::previewUpcoming(), chacune retirable (✕)
// avant confirmation — rien n'est ajouté au planning tant que l'utilisateur n'a pas validé
// (useApplyAutofill, voir applyPreview() côté serveur).
export function AutofillModal({ visible, onClose, categories, resumeItems }: Props) {
  const preview = usePreviewAutofill();
  const apply = useApplyAutofill();
  const resuggest = useResuggestAutofillItem();
  const navigation = useNavigation();
  const [step, setStep] = useState<Step>('dates');
  const [start, setStart] = useState(() => saturdayOnOrAfterIso(todayIso()));
  const [end, setEnd] = useState(() => addDaysIso(start, 6));
  const [items, setItems] = useState<AutofillPreviewItem[]>([]);
  // Ligne en cours de régénération (bouton "Autre proposition") — une seule à la fois,
  // pour ne pas construire excludeRecipeIds à partir d'un état en train de changer.
  const [regeneratingIndex, setRegeneratingIndex] = useState<number | null>(null);
  // Ligne dont le composeur "Créer une recette IA" est ouvert, et texte saisi dedans.
  const [aiComposerIndex, setAiComposerIndex] = useState<number | null>(null);
  const [aiText, setAiText] = useState('');
  // Photo de la proposition tapée pour aperçu en grand (voir Modal dédiée en bas de rendu).
  const [previewPhoto, setPreviewPhoto] = useState<string | null>(null);

  useEffect(() => {
    if (!visible) return;
    setRegeneratingIndex(null);
    setAiComposerIndex(null);
    setAiText('');
    if (resumeItems) {
      setItems(resumeItems);
      setStep('review');
      return;
    }
    setStep('dates');
    const defaultStart = saturdayOnOrAfterIso(todayIso());
    setStart(defaultStart);
    setEnd(addDaysIso(defaultStart, 6));
    setItems([]);
  }, [visible, resumeItems]);

  const days = diffDaysIso(end, start) + 1;

  function shiftStart(delta: number) {
    const next = addDaysIso(start, delta);
    setStart(next);
    if (diffDaysIso(end, next) < 0) setEnd(next);
    if (diffDaysIso(end, next) + 1 > MAX_DAYS) setEnd(addDaysIso(next, MAX_DAYS - 1));
  }

  function shiftEnd(delta: number) {
    const next = addDaysIso(end, delta);
    if (diffDaysIso(next, start) < 0) return;
    if (diffDaysIso(next, start) + 1 > MAX_DAYS) return;
    setEnd(next);
  }

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

  function goToReview() {
    preview.mutate(
      { startDate: start, days },
      {
        onSuccess: (result) => { setItems(result.items); setStep('review'); },
        onError: reportError,
      },
    );
  }

  function removeItem(index: number) {
    setItems((prev) => prev.filter((_, i) => i !== index));
  }

  // Exclut toutes les recettes déjà affichées dans la popin (celle à remplacer comprise)
  // pour ne jamais reproposer un doublon visible à l'écran — voir resuggestItem() côté serveur.
  function regenerateItem(index: number) {
    const target = items[index];
    const excludeRecipeIds = items.map((it) => it.recipeId).filter((id): id is number => id !== null);

    setRegeneratingIndex(index);
    resuggest.mutate(
      { category: target.category, plannedDate: target.plannedDate, excludeRecipeIds },
      {
        onSuccess: (result) => {
          setRegeneratingIndex(null);
          if (!result.item) {
            showAlert('Info', 'Aucune autre recette disponible pour ce créneau.');
            return;
          }
          setItems((prev) => prev.map((it, i) => (i === index ? result.item! : it)));
        },
        onError: (err) => { setRegeneratingIndex(null); reportError(err); },
      },
    );
  }

  function confirm() {
    apply.mutate(items, { onSuccess: onClose, onError: reportError });
  }

  function toggleAiComposer(index: number) {
    if (aiComposerIndex === index) {
      setAiComposerIndex(null);
      return;
    }
    setAiComposerIndex(index);
    setAiText('');
  }

  // Lance le processus complet de création de recette (RecipeImportScreen, wizard 6 étapes
  // — mêmes endpoints IA que l'import photo/URL/texte) à partir du texte saisi, puis revient
  // ici avec cette proposition remplacée par la recette créée — voir pendingAutofillResume.ts
  // et returnTo="planning" dans RecipeImportScreen.tsx. Quitte l'écran (mobile-web : vrai
  // rechargement de page) : l'état de la popin est donc persisté avant de partir.
  function createAiRecipe(index: number) {
    const text = aiText.trim();
    if (!text) return;

    savePendingAutofillResume(items, index);
    if (Platform.OS === 'web') {
      window.location.href = `${RECIPE_IMPORT_PATH}?quickText=${encodeURIComponent(text)}&returnTo=planning`;
    } else {
      (navigation as any).navigate('RecipeImport', { quickText: text, returnTo: 'planning' });
    }
  }

  function categoryInfo(value: string): CategoryOption {
    return categories.find((c) => c.value === value) ?? { value, label: value, gradient: [colors.primary, colors.primary] };
  }

  function itemDateLabel(item: AutofillPreviewItem): string {
    if (!item.plannedDate) return categoryInfo(item.category).label;
    const { weekday, short } = dayInfo(item.plannedDate);
    return `${weekday} ${short} · ${categoryInfo(item.category).label}`;
  }

  function renderDateStepper(label: string, iso: string, onShift: (delta: number) => void, disableDown: boolean) {
    const { weekday, short } = dayInfo(iso);
    return (
      <View style={styles.dateRow}>
        <Text style={styles.fieldLabel}>{label}</Text>
        <View style={styles.stepper}>
          <Pressable
            style={[styles.stepBtn, disableDown && styles.stepBtnDisabled]}
            disabled={disableDown}
            onPress={() => onShift(-1)}
            hitSlop={6}
          >
            <Ionicons name="remove" size={14} color={disableDown ? colors.border : colors.textMuted} />
          </Pressable>
          <Text style={styles.dateText}>{weekday} {short}</Text>
          <Pressable style={styles.stepBtn} onPress={() => onShift(1)} hitSlop={6}>
            <Ionicons name="add" size={14} color={colors.textMuted} />
          </Pressable>
        </View>
      </View>
    );
  }

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <View style={{ flex: 1 }}>
              <Text style={styles.title}>Suggestion d'idées</Text>
              <Text style={styles.subtitle}>
                {step === 'dates' ? 'Déjeuner et dîner de la période choisie' : `${items.length} proposition${items.length > 1 ? 's' : ''} à valider`}
              </Text>
            </View>
            <Pressable onPress={onClose} hitSlop={8} style={styles.closeBtn}>
              <Ionicons name="close" size={16} color={colors.textMuted} />
            </Pressable>
          </View>

          {step === 'dates' ? (
            <View style={styles.stepGap}>
              {renderDateStepper('Du', start, shiftStart, false)}
              {renderDateStepper('Au', end, shiftEnd, diffDaysIso(end, start) <= 0)}
              <Text style={styles.hint}>{days} jour{days > 1 ? 's' : ''}</Text>

              <View style={styles.actions}>
                <Pressable style={styles.ghostBtn} disabled={preview.isPending} onPress={onClose}>
                  <Text style={styles.ghostBtnText}>Annuler</Text>
                </Pressable>
                <Pressable
                  style={[styles.primaryBtn, preview.isPending && styles.primaryBtnDisabled]}
                  disabled={preview.isPending}
                  onPress={goToReview}
                >
                  {preview.isPending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryBtnText}>Voir les propositions</Text>}
                </Pressable>
              </View>
            </View>
          ) : (
            <View style={styles.stepGap}>
              {items.length === 0 ? (
                <Text style={styles.hint}>Rien à proposer sur cette période (créneaux déjà remplis, ou catalogue de recettes épuisé pour éviter les doublons).</Text>
              ) : (
                <ScrollView style={styles.list} keyboardShouldPersistTaps="handled">
                  {items.map((item, index) => {
                    const info = categoryInfo(item.category);
                    const photo = imageUri(item.imageUrl);
                    const tint = SOURCE_TINT[item.source] ?? SOURCE_TINT.catalog;
                    const isRegenerating = regeneratingIndex === index;
                    const rowDisabled = regeneratingIndex !== null;
                    const composerOpen = aiComposerIndex === index;
                    return (
                      <View key={`${item.category}-${item.plannedDate ?? 'x'}-${index}`} style={styles.itemCard}>
                        <View style={styles.itemRow}>
                          {photo ? (
                            <Pressable onPress={() => setPreviewPhoto(photo)} hitSlop={4}>
                              <Image source={{ uri: photo }} style={styles.itemPhoto} />
                            </Pressable>
                          ) : (
                            <View style={[styles.itemPhoto, styles.itemPhotoFallback]}>
                              <View style={[styles.itemDot, { backgroundColor: info.gradient[1] }]} />
                            </View>
                          )}
                          <View style={{ flex: 1 }}>
                            <Text style={styles.itemDate}>{itemDateLabel(item)}</Text>
                            <Text style={styles.itemTitle} numberOfLines={1}>{item.title}</Text>
                            <View style={[styles.sourceBadge, { backgroundColor: tint.bg }]}>
                              <Text style={[styles.sourceBadgeText, { color: tint.fg }]}>{SOURCE_LABEL[item.source] ?? item.source}</Text>
                            </View>
                          </View>
                          <Pressable
                            onPress={() => toggleAiComposer(index)}
                            disabled={rowDisabled}
                            hitSlop={8}
                            style={[styles.itemActionBtn, composerOpen && styles.itemActionBtnOn, rowDisabled && styles.itemActionBtnDisabled]}
                            {...(Platform.OS === 'web' ? { title: 'Créer une recette IA' } : null)}
                          >
                            <Ionicons name="sparkles-outline" size={14} color={composerOpen ? '#fff' : colors.primary} />
                          </Pressable>
                          <Pressable
                            onPress={() => regenerateItem(index)}
                            disabled={rowDisabled}
                            hitSlop={8}
                            style={[styles.itemActionBtn, rowDisabled && styles.itemActionBtnDisabled]}
                            {...(Platform.OS === 'web' ? { title: 'Autre proposition' } : null)}
                          >
                            {isRegenerating ? <ActivityIndicator size="small" color={colors.primary} /> : <Ionicons name="refresh" size={14} color={colors.primary} />}
                          </Pressable>
                          <Pressable
                            onPress={() => removeItem(index)}
                            disabled={rowDisabled}
                            hitSlop={8}
                            style={[styles.itemActionBtn, rowDisabled && styles.itemActionBtnDisabled]}
                          >
                            <Ionicons name="close" size={14} color={colors.textMuted} />
                          </Pressable>
                        </View>

                        {composerOpen ? (
                          <View style={styles.aiComposer}>
                            <TextInput
                              style={styles.aiComposerInput}
                              value={aiText}
                              onChangeText={setAiText}
                              placeholder="Ex. : poulet basquaise, riz…"
                              placeholderTextColor={colors.textMuted}
                              autoFocus
                            />
                            <Pressable
                              style={[styles.aiComposerBtn, aiText.trim() === '' && styles.primaryBtnDisabled]}
                              disabled={aiText.trim() === ''}
                              onPress={() => createAiRecipe(index)}
                            >
                              <Text style={styles.primaryBtnText}>Créer</Text>
                            </Pressable>
                          </View>
                        ) : null}
                      </View>
                    );
                  })}
                </ScrollView>
              )}

              <View style={styles.actions}>
                <Pressable style={styles.ghostBtn} disabled={apply.isPending} onPress={() => setStep('dates')}>
                  <Text style={styles.ghostBtnText}>Retour</Text>
                </Pressable>
                <Pressable
                  style={[styles.primaryBtn, (apply.isPending || items.length === 0) && styles.primaryBtnDisabled]}
                  disabled={apply.isPending || items.length === 0}
                  onPress={confirm}
                >
                  {apply.isPending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryBtnText}>Ajouter ({items.length})</Text>}
                </Pressable>
              </View>
            </View>
          )}
        </Pressable>
      </Pressable>

      <Modal visible={!!previewPhoto} transparent animationType="fade" onRequestClose={() => setPreviewPhoto(null)}>
        <Pressable style={styles.previewBackdrop} onPress={() => setPreviewPhoto(null)}>
          {previewPhoto ? <Image source={{ uri: previewPhoto }} style={styles.previewImage} resizeMode="contain" /> : null}
        </Pressable>
      </Modal>
    </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 },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: 2 },
  closeBtn: { width: 30, height: 30, borderRadius: radii.pill, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' },
  stepGap: { gap: spacing.sm },
  fieldLabel: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.textMuted },
  dateRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  stepper: {
    flexDirection: 'row', alignItems: 'center', gap: spacing.sm,
    backgroundColor: colors.background, borderWidth: 1, borderColor: colors.border, borderRadius: radii.pill,
    paddingVertical: 6, paddingHorizontal: 8,
  },
  stepBtn: {
    width: 24, height: 24, borderRadius: radii.pill, borderWidth: 1, borderColor: colors.border,
    backgroundColor: colors.card, alignItems: 'center', justifyContent: 'center',
  },
  stepBtnDisabled: { opacity: 0.5 },
  dateText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text, minWidth: 64, textAlign: 'center' },
  hint: { ...typography.caption, color: colors.textMuted, textAlign: 'center', paddingVertical: spacing.sm },
  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 },
  list: { maxHeight: 380 },
  itemCard: {
    paddingVertical: 10, paddingHorizontal: spacing.sm, borderRadius: radii.sm,
    borderWidth: 1, borderColor: colors.border, marginBottom: 6,
  },
  itemRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  itemDot: { width: 8, height: 8, borderRadius: 4 },
  itemPhoto: { width: 40, height: 40, borderRadius: radii.sm, backgroundColor: colors.background },
  itemPhotoFallback: { alignItems: 'center', justifyContent: 'center' },
  itemDate: { ...typography.caption, fontSize: 11, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 0.3, color: colors.textMuted },
  itemTitle: { ...typography.body, fontSize: 14, fontWeight: '600', color: colors.text, marginTop: 2 },
  sourceBadge: { alignSelf: 'flex-start', borderRadius: radii.pill, paddingVertical: 2, paddingHorizontal: 7, marginTop: 4 },
  sourceBadgeText: { fontSize: 10, fontWeight: '700' },
  itemActionBtn: { width: 26, height: 26, borderRadius: radii.pill, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' },
  itemActionBtnOn: { backgroundColor: colors.primary },
  itemActionBtnDisabled: { opacity: 0.5 },
  aiComposer: { flexDirection: 'row', gap: spacing.xs, marginTop: spacing.sm },
  aiComposerInput: {
    flex: 1, borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm,
    paddingHorizontal: spacing.sm, paddingVertical: 8, color: colors.text, backgroundColor: colors.background, fontSize: 13.5,
  },
  aiComposerBtn: { paddingHorizontal: spacing.md, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  previewBackdrop: { flex: 1, backgroundColor: 'rgba(10, 10, 14, 0.92)', alignItems: 'center', justifyContent: 'center' },
  previewImage: { width: '100%', height: '80%' },
});
