import { useMemo, useState } from 'react';
import {
  View,
  Text,
  Pressable,
  StyleSheet,
  ScrollView,
  ActivityIndicator,
  RefreshControl,
  TextInput,
  Platform,
  Modal,
  useWindowDimensions,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useRecipes } from '../hooks/useRecipes';
import { colors, spacing, radii, typography } from '../../../theme';
import { RECIPE_CATEGORY_OPTIONS } from '../utils/category';
import { RecipeCard } from '../components/RecipeCard';

// Calque `templates/recipe_catalog/index.html.twig` / `assets/js/recipe-catalog.js` :
// bascule Mes recettes / Toute la base, recherche + filtre catégorie (client, comme
// le web), grille de cartes. "Importer une recette"/"Saisie rapide" ouvrent
// `RecipeImportScreen.tsx` (portage natif du wizard d'import, voir ce fichier) :
// navigation in-app en natif, navigation de page (même route Symfony, qui monte
// désormais ce même écran react-native-web) sur mobile-web.
const IMPORT_PATH = '/import/recette';

export function RecipeCatalogScreen() {
  const [scope, setScope] = useState<'mine' | 'all'>('all');
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState<string>('all');
  const [quickAddOpen, setQuickAddOpen] = useState(false);
  const [quickAddText, setQuickAddText] = useState('');
  const navigation = useNavigation();
  const { width } = useWindowDimensions();
  const columns = width >= 700 ? 2 : 1;

  function openImport() {
    if (Platform.OS === 'web') {
      window.location.href = IMPORT_PATH;
    } else {
      (navigation as any).navigate('RecipeImport');
    }
  }

  function submitQuickAdd() {
    const text = quickAddText.trim();
    if (!text) return;
    setQuickAddOpen(false);
    setQuickAddText('');
    if (Platform.OS === 'web') {
      window.location.href = `${IMPORT_PATH}?quickText=${encodeURIComponent(text)}`;
    } else {
      (navigation as any).navigate('RecipeImport', { quickText: text });
    }
  }

  const { data, isLoading, error, refetch, isRefetching } = useRecipes(scope);

  const recipes = data?.recipes ?? [];
  const filtered = useMemo(() => {
    const query = search.trim().toLowerCase();
    return recipes.filter((r) => {
      const matchesSearch = query === '' || r.name.toLowerCase().includes(query);
      const matchesCategory = category === 'all' || r.category === category;
      return matchesSearch && matchesCategory;
    });
  }, [recipes, search, category]);

  function openRecipe(id: number) {
    if (Platform.OS === 'web') {
      window.location.href = `/recettes/${id}`;
      return;
    }
    (navigation as any).navigate('RecipeDetail', { id });
  }

  if (isLoading) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.center}>
        <Text style={typography.body}>Impossible de charger les recettes.</Text>
      </View>
    );
  }

  return (
    <>
    <ScrollView
      style={styles.container}
      contentContainerStyle={styles.content}
      refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor={colors.primary} />}
    >
      <View style={styles.header}>
        <Text style={styles.title}>{scope === 'all' ? 'Toute la base' : 'Mes recettes'}</Text>
        <Text style={styles.subtitle}>
          {scope === 'all'
            ? "Parcourez les recettes de tous les utilisateurs — ajoutez-les à vos favoris pour les retrouver dans \"Mes recettes\"."
            : 'Parcourez vos recettes et vos favoris, et consultez leur résumé diététique.'}
        </Text>
      </View>

      <View style={styles.scopeToggle}>
        <Pressable style={[styles.scopeBtn, scope === 'mine' && styles.scopeBtnActive]} onPress={() => setScope('mine')}>
          <Text style={[styles.scopeBtnText, scope === 'mine' && styles.scopeBtnTextActive]}>Mes recettes</Text>
        </Pressable>
        <Pressable style={[styles.scopeBtn, scope === 'all' && styles.scopeBtnActive]} onPress={() => setScope('all')}>
          <Text style={[styles.scopeBtnText, scope === 'all' && styles.scopeBtnTextActive]}>Toute la base</Text>
        </Pressable>
      </View>

      <View style={styles.importRow}>
        <Pressable style={styles.importBtn} onPress={openImport}>
          <Ionicons name="download-outline" size={15} color={colors.text} />
          <Text style={styles.importBtnText}>Importer une recette</Text>
        </Pressable>
        <Pressable style={styles.quickAddBtn} onPress={() => setQuickAddOpen(true)}>
          <Ionicons name="sparkles" size={15} color="#fff" />
          <Text style={styles.quickAddBtnText}>Saisie rapide</Text>
        </Pressable>
      </View>

      {recipes.length === 0 ? (
        <Text style={styles.emptyText}>
          {scope === 'all' ? 'Aucune recette dans la base pour le moment.' : "Vous n'avez pas encore de recette."}
        </Text>
      ) : (
        <>
          <View style={styles.searchRow}>
            <Ionicons name="search" size={15} color={colors.textMuted} />
            <TextInput
              style={styles.searchInput}
              value={search}
              onChangeText={setSearch}
              placeholder="Rechercher une recette…"
              placeholderTextColor={colors.textMuted}
            />
          </View>

          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.chipsRow}>
            <Pressable style={[styles.chip, category === 'all' && styles.chipActive]} onPress={() => setCategory('all')}>
              <Text style={[styles.chipText, category === 'all' && styles.chipTextActive]}>Toutes</Text>
            </Pressable>
            {RECIPE_CATEGORY_OPTIONS.map((opt) => (
              <Pressable
                key={opt.value}
                style={[styles.chip, category === opt.value && styles.chipActive]}
                onPress={() => setCategory(opt.value)}
              >
                <Text style={[styles.chipText, category === opt.value && styles.chipTextActive]}>{opt.label}</Text>
              </Pressable>
            ))}
          </ScrollView>

          {filtered.length === 0 ? (
            <Text style={styles.emptyText}>Aucune recette ne correspond à votre recherche.</Text>
          ) : (
            <View style={styles.grid}>
              {filtered.map((recipe) => (
                <View key={recipe.id} style={{ width: columns === 2 ? '48.5%' : '100%' }}>
                  <RecipeCard recipe={recipe} onPress={() => openRecipe(recipe.id)} />
                </View>
              ))}
            </View>
          )}
        </>
      )}
    </ScrollView>

    <Modal visible={quickAddOpen} transparent animationType="fade" onRequestClose={() => setQuickAddOpen(false)}>
      <Pressable style={styles.qaBackdrop} onPress={() => setQuickAddOpen(false)}>
        <Pressable style={styles.qaSheet} onPress={(e) => e.stopPropagation()}>
          <View style={styles.qaHeader}>
            <Text style={styles.qaTitle}>Saisie rapide</Text>
            <Pressable onPress={() => setQuickAddOpen(false)} hitSlop={8}>
              <Ionicons name="close" size={18} color={colors.textMuted} />
            </Pressable>
          </View>
          <Text style={styles.qaHelp}>
            Décrivez la recette du jour en quelques mots — ingrédients, quantités, étapes. L'IA structure tout et
            prépare la recette pour vérification, comme un import classique.
          </Text>
          <TextInput
            style={styles.qaInput}
            value={quickAddText}
            onChangeText={setQuickAddText}
            placeholder="Ex. : Poulet grillé, riz basmati, brocolis vapeur — 20 min de cuisson…"
            placeholderTextColor={colors.textMuted}
            multiline
            numberOfLines={5}
          />
          <View style={styles.qaActions}>
            <Pressable style={styles.qaGhostBtn} onPress={() => setQuickAddOpen(false)}>
              <Text style={styles.qaGhostBtnText}>Annuler</Text>
            </Pressable>
            <Pressable
              style={[styles.qaPrimaryBtn, quickAddText.trim() === '' && styles.qaPrimaryBtnDisabled]}
              disabled={quickAddText.trim() === ''}
              onPress={submitQuickAdd}
            >
              <Text style={styles.qaPrimaryBtnText}>Analyser avec l'IA</Text>
            </Pressable>
          </View>
        </Pressable>
      </Pressable>
    </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  // Sur web, la coquille (App.web.tsx / .mw-page) est déjà en fond blanc — ce
  // `colors.background` (gris) restait visible dans les zones non couvertes
  // par une carte opaque. En natif, on garde le fond gris habituel de l'appli.
  container: { flex: 1, backgroundColor: Platform.OS === 'web' ? '#fff' : colors.background },
  // Sur mobile-web, la coquille (assets/styles/mobile-web-mount.css) n'a
  // plus aucune marge propre — l'écran doit se rapprocher au maximum des
  // bords lui-même (juste 2px, demande explicite) ; en natif on garde la
  // marge normale.
  content: { paddingHorizontal: Platform.OS === 'web' ? 2 : spacing.lg, paddingVertical: spacing.lg, gap: spacing.md },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: Platform.OS === 'web' ? '#fff' : colors.background },
  header: { gap: 4 },
  title: { ...typography.title, fontSize: 26, color: colors.text },
  subtitle: { ...typography.body, color: colors.textMuted },
  scopeToggle: { flexDirection: 'row', gap: 8 },
  scopeBtn: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: spacing.sm,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.card,
  },
  scopeBtnActive: { backgroundColor: '#eef0fe', borderColor: colors.primary },
  scopeBtnText: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  scopeBtnTextActive: { color: colors.primary },
  importRow: { flexDirection: 'row', gap: spacing.sm },
  importBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6, paddingVertical: spacing.sm, paddingHorizontal: spacing.md,
    borderRadius: radii.md, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.card,
  },
  importBtnText: { fontSize: 13, fontWeight: '700', color: colors.text },
  quickAddBtn: {
    flexDirection: 'row', alignItems: 'center', gap: 6, paddingVertical: spacing.sm, paddingHorizontal: spacing.md,
    borderRadius: radii.md, backgroundColor: colors.primary,
  },
  quickAddBtnText: { fontSize: 13, fontWeight: '700', color: '#fff' },
  emptyText: { ...typography.body, color: colors.textMuted, textAlign: 'center', paddingVertical: spacing.lg },
  searchRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    height: 42,
    backgroundColor: colors.card,
  },
  searchInput: { flex: 1, ...typography.body, fontSize: 14, color: colors.text },
  chipsRow: { gap: 8, paddingVertical: 2 },
  chip: {
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.card,
    paddingHorizontal: spacing.md,
    paddingVertical: 8,
    borderRadius: radii.pill,
  },
  chipActive: { backgroundColor: '#eef0fe', borderColor: colors.primary },
  chipText: { fontSize: 13, fontWeight: '600', color: colors.textMuted },
  chipTextActive: { color: colors.primary },
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.md },
  qaBackdrop: { flex: 1, backgroundColor: 'rgba(20, 20, 26, 0.4)', justifyContent: 'center', padding: spacing.lg },
  qaSheet: { backgroundColor: colors.card, borderRadius: radii.xl, padding: spacing.lg, gap: spacing.sm },
  qaHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  qaTitle: { ...typography.title, fontSize: 17, color: colors.text },
  qaHelp: { ...typography.caption, fontSize: 12.5, color: colors.textMuted },
  qaInput: {
    borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, padding: spacing.sm,
    color: colors.text, backgroundColor: colors.background, minHeight: 110, textAlignVertical: 'top',
  },
  qaActions: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.xs },
  qaGhostBtn: { paddingVertical: spacing.sm + 2, paddingHorizontal: spacing.md, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border, alignItems: 'center', justifyContent: 'center' },
  qaGhostBtnText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.textMuted },
  qaPrimaryBtn: { flex: 1, paddingVertical: spacing.sm + 2, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  qaPrimaryBtnDisabled: { opacity: 0.5 },
  qaPrimaryBtnText: { color: '#fff', fontWeight: '700', fontSize: 14 },
});
