import { useState } from 'react';
import { View, Text, Pressable, StyleSheet, ScrollView, ActivityIndicator, TextInput, Platform } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { colors, spacing, radii, typography } from '../../../theme';
import { LookupParams, useFoodLookup } from '../hooks/useFoodLookup';
import { FoodLookupHistoryEntry } from '../../../api/foodLookup';
import { ProductScanModal } from '../components/ProductScanModal';
import { FoodLookupItemCard } from '../components/FoodLookupItemCard';
import { ProductCard } from '../../../components/ProductCard';

export function FoodLookupScreen() {
  const [queryInput, setQueryInput] = useState('');
  const [params, setParams] = useState<LookupParams>({});
  const [scanMode, setScanMode] = useState<'barcode' | 'photo' | null>(null);
  const { data, isLoading, isFetching } = useFoodLookup(params);

  function search(q: string) {
    if (q.trim() === '') return;
    setParams({ q: q.trim() });
  }

  function openHistoryEntry(entry: FoodLookupHistoryEntry) {
    if (entry.isBarcode && entry.barcode) {
      setParams({ code: entry.barcode });
    } else if (entry.query) {
      setQueryInput(entry.query);
      setParams({ q: entry.query });
    }
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <View>
        <Text style={styles.title}>Produits / Aliments</Text>
        <Text style={styles.subtitle}>Recherchez un aliment et comparez ses valeurs nutritionnelles entre Ciqual et Open Food Facts.</Text>
      </View>

      <View style={styles.searchRow}>
        <TextInput
          style={styles.input}
          placeholder="Ex. : yaourt nature, banane, poulet…"
          placeholderTextColor={colors.textMuted}
          value={queryInput}
          onChangeText={setQueryInput}
          onSubmitEditing={() => search(queryInput)}
          autoCapitalize="none"
        />
        <Pressable style={styles.searchButton} onPress={() => search(queryInput)}>
          <Ionicons name="search" size={18} color="#fff" />
        </Pressable>
      </View>

      <View style={styles.scanRow}>
        <Pressable style={styles.scanButton} onPress={() => setScanMode('barcode')}>
          <Ionicons name="barcode-outline" size={17} color={colors.primary} />
          <Text style={styles.scanButtonText}>Scanner un code-barres</Text>
        </Pressable>
        <Pressable style={styles.scanButton} onPress={() => setScanMode('photo')}>
          <Ionicons name="camera-outline" size={17} color={colors.primary} />
          <Text style={styles.scanButtonText}>Produit IA</Text>
        </Pressable>
      </View>

      {data && data.history.length > 0 ? (
        <View style={styles.card}>
          <Text style={styles.cardTitle}>Mes produits récents</Text>
          {data.history.map((entry) => (
            <Pressable key={entry.id} style={styles.historyRow} onPress={() => openHistoryEntry(entry)}>
              <Ionicons name={entry.isBarcode ? 'barcode-outline' : 'camera-outline'} size={16} color={colors.textMuted} />
              <Text style={styles.historyLabel} numberOfLines={1}>{entry.label}</Text>
            </Pressable>
          ))}
        </View>
      ) : null}

      {isLoading || isFetching ? (
        <ActivityIndicator color={colors.primary} />
      ) : null}

      {data?.notice ? <Text style={styles.notice}>{data.notice}</Text> : null}

      {data?.results?.product ? <ProductCard product={data.results.product} /> : null}

      {data?.results && !data.results.product ? (
        <View style={styles.card}>
          <Text style={styles.cardTitle}>Ciqual (ANSES)</Text>
          {data.results.ciqual.length === 0 ? (
            <Text style={styles.hint}>Aucun résultat.</Text>
          ) : (
            <View style={styles.itemList}>
              {data.results.ciqual.map((item, index) => <FoodLookupItemCard key={`ciqual-${index}`} item={item} />)}
            </View>
          )}
        </View>
      ) : null}

      {data?.results ? (
        <View style={styles.card}>
          <Text style={styles.cardTitle}>Open Food Facts</Text>
          {data.results.openFoodFacts.length === 0 ? (
            <Text style={styles.hint}>Aucun résultat.</Text>
          ) : (
            <View style={styles.itemList}>
              {data.results.openFoodFacts.map((item, index) => <FoodLookupItemCard key={`off-${index}`} item={item} />)}
            </View>
          )}
        </View>
      ) : null}

      <ProductScanModal
        visible={scanMode !== null}
        mode={scanMode ?? 'barcode'}
        onClose={() => setScanMode(null)}
        onBarcodeFound={(barcode) => { setScanMode(null); setParams({ code: barcode, fromScan: true }); }}
        onPhotoIdentified={(name) => { setScanMode(null); setQueryInput(name); setParams({ q: name, fromScan: true }); }}
      />
    </ScrollView>
  );
}

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 },
  title: { ...typography.title, color: colors.text },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: spacing.xs },
  searchRow: { flexDirection: 'row', gap: spacing.sm },
  input: {
    flex: 1,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    color: colors.text,
    backgroundColor: colors.card,
  },
  searchButton: { width: 44, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  scanRow: { flexDirection: 'row', gap: spacing.sm },
  scanButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.xs,
    paddingVertical: spacing.sm,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.border,
    backgroundColor: colors.card,
  },
  scanButtonText: { ...typography.body, fontSize: 13, fontWeight: '700', color: colors.primary },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  cardTitle: { ...typography.body, fontWeight: '700', color: colors.text },
  historyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, paddingVertical: 4 },
  historyLabel: { ...typography.body, fontSize: 14, color: colors.text, flex: 1 },
  notice: { ...typography.caption, color: colors.danger, textAlign: 'center' },
  hint: { ...typography.caption, color: colors.textMuted },
  itemList: { gap: spacing.sm },
});
