import { useMemo, useState } from 'react';
import { View, Text, Pressable, TextInput, StyleSheet, Modal } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { colors, spacing, radii, typography } from '../../../../theme';
import { FormIngredient, UNITS } from './types';

type Props = {
  ingredients: FormIngredient[];
  appliances: string[];
  applianceCatalog: string[];
  onChangeIngredients: (ingredients: FormIngredient[]) => void;
  onChangeAppliances: (appliances: string[]) => void;
  onNext: () => void;
  onBack: () => void;
};

// Calque `templates/recipe_import/index.html.twig` (panneau 3 "Ingrédients") — lignes
// ingrédient/quantité/unité + tags appareils avec recherche dans le catalogue.
export function IngredientsStep({
  ingredients, appliances, applianceCatalog, onChangeIngredients, onChangeAppliances, onNext, onBack,
}: Props) {
  const [unitPickerFor, setUnitPickerFor] = useState<number | null>(null);
  const [appQuery, setAppQuery] = useState('');

  function updateIngredient(index: number, patch: Partial<FormIngredient>) {
    const next = [...ingredients];
    next[index] = { ...next[index], ...patch };
    onChangeIngredients(next);
  }

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

  function addIngredient() {
    onChangeIngredients([...ingredients, { name: '', nameEn: null, ciqualCode: null, quantity: '', unit: 'g' }]);
  }

  const applianceSuggestions = useMemo(() => {
    const q = appQuery.trim().toLowerCase();
    const added = new Set(appliances.map((a) => a.toLowerCase()));
    const pool = applianceCatalog.filter((name) => !added.has(name.toLowerCase()));
    return (q ? pool.filter((name) => name.toLowerCase().includes(q)) : pool).slice(0, 7);
  }, [appQuery, appliances, applianceCatalog]);

  function addAppliance(name: string) {
    onChangeAppliances([...appliances, name]);
    setAppQuery('');
  }

  function removeAppliance(name: string) {
    onChangeAppliances(appliances.filter((a) => a !== name));
  }

  return (
    <View style={styles.wrap}>
      <Text style={styles.kick}>Étape 4 / 6</Text>
      <Text style={styles.h2}>Ingrédients</Text>
      <Text style={styles.help}>Vérifiez les quantités et unités extraites par l'IA.</Text>

      <View style={styles.list}>
        {ingredients.map((ing, i) => (
          <View key={i} style={styles.row}>
            <TextInput
              style={[styles.input, styles.nameInput]}
              value={ing.name}
              onChangeText={(name) => updateIngredient(i, { name, nameEn: null, ciqualCode: null })}
              placeholder="Ingrédient"
              placeholderTextColor={colors.textMuted}
            />
            <TextInput
              style={[styles.input, styles.qtyInput]}
              value={ing.quantity}
              onChangeText={(quantity) => updateIngredient(i, { quantity: quantity.replace(/[^0-9.,]/g, '') })}
              placeholder="Qté"
              placeholderTextColor={colors.textMuted}
              keyboardType="decimal-pad"
            />
            <Pressable style={styles.unitBtn} onPress={() => setUnitPickerFor(i)}>
              <Text style={styles.unitBtnText}>{UNITS.find((u) => u.value === ing.unit)?.label ?? ing.unit}</Text>
              <Ionicons name="chevron-down" size={13} color={colors.textMuted} />
            </Pressable>
            <Pressable onPress={() => removeIngredient(i)} hitSlop={6}>
              <Ionicons name="trash-outline" size={17} color={colors.textMuted} />
            </Pressable>
          </View>
        ))}
      </View>

      <Pressable style={styles.addBtn} onPress={addIngredient}>
        <Ionicons name="add" size={16} color={colors.primary} />
        <Text style={styles.addBtnText}>Ajouter un ingrédient</Text>
      </Pressable>

      <View style={styles.divider} />

      <Text style={styles.sectionLbl}>Appareils</Text>
      <View style={styles.chipRow}>
        {appliances.map((name) => (
          <Pressable key={name} style={styles.chipOn} onPress={() => removeAppliance(name)}>
            <Text style={styles.chipOnText}>{name}</Text>
            <Ionicons name="close" size={13} color={colors.primary} />
          </Pressable>
        ))}
      </View>
      <TextInput
        style={styles.input}
        value={appQuery}
        onChangeText={setAppQuery}
        placeholder="Rechercher un appareil…"
        placeholderTextColor={colors.textMuted}
        autoCapitalize="none"
      />
      {appQuery.trim().length > 0 && (
        <View style={styles.acBox}>
          {applianceSuggestions.length === 0 ? (
            <Text style={styles.acEmpty}>Aucun appareil correspondant</Text>
          ) : (
            applianceSuggestions.map((name) => (
              <Pressable key={name} style={styles.acItem} onPress={() => addAppliance(name)}>
                <Text style={styles.acItemText}>{name}</Text>
              </Pressable>
            ))
          )}
        </View>
      )}

      <View style={styles.actions}>
        <Pressable style={styles.ghostBtn} onPress={onBack}>
          <Text style={styles.ghostBtnText}>Retour</Text>
        </Pressable>
        <Pressable style={styles.primaryBtn} onPress={onNext}>
          <Text style={styles.primaryBtnText}>Vérifier →</Text>
        </Pressable>
      </View>

      <Modal visible={unitPickerFor !== null} transparent animationType="fade" onRequestClose={() => setUnitPickerFor(null)}>
        <Pressable style={styles.modalBackdrop} onPress={() => setUnitPickerFor(null)}>
          <Pressable style={styles.modalSheet} onPress={(e) => e.stopPropagation()}>
            <Text style={styles.modalTitle}>Unité</Text>
            {UNITS.map((u) => (
              <Pressable
                key={u.value}
                style={styles.modalOption}
                onPress={() => {
                  if (unitPickerFor !== null) updateIngredient(unitPickerFor, { unit: u.value });
                  setUnitPickerFor(null);
                }}
              >
                <Text style={styles.modalOptionText}>{u.label}</Text>
              </Pressable>
            ))}
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { gap: spacing.sm },
  kick: { ...typography.caption, fontSize: 11.5, fontWeight: '800', color: colors.primary, textTransform: 'uppercase', letterSpacing: 0.5 },
  h2: { ...typography.title, fontSize: 20, color: colors.text },
  help: { ...typography.body, fontSize: 13.5, color: colors.textMuted, marginBottom: spacing.xs },
  list: { gap: spacing.xs },
  row: { flexDirection: 'row', alignItems: 'center', gap: 6 },
  input: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: spacing.sm, paddingVertical: spacing.sm, color: colors.text, backgroundColor: colors.card },
  nameInput: { flex: 1 },
  qtyInput: { width: 60, textAlign: 'center' },
  unitBtn: { flexDirection: 'row', alignItems: 'center', gap: 3, borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, paddingHorizontal: 8, paddingVertical: spacing.sm, backgroundColor: colors.card },
  unitBtnText: { fontSize: 12.5, fontWeight: '600', color: colors.text },
  addBtn: { flexDirection: 'row', alignItems: 'center', gap: 6, alignSelf: 'flex-start', paddingVertical: 6 },
  addBtnText: { fontSize: 13.5, fontWeight: '700', color: colors.primary },
  divider: { height: 1, backgroundColor: colors.border, marginVertical: spacing.xs },
  sectionLbl: { fontSize: 12, fontWeight: '800', color: colors.textMuted, textTransform: 'uppercase', letterSpacing: 0.4 },
  chipRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  chipOn: { flexDirection: 'row', alignItems: 'center', gap: 5, backgroundColor: '#eef0fe', borderRadius: radii.pill, paddingVertical: 6, paddingHorizontal: 12 },
  chipOnText: { fontSize: 12.5, fontWeight: '700', color: colors.primary },
  acBox: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.sm, backgroundColor: colors.card, overflow: 'hidden' },
  acEmpty: { padding: spacing.sm, fontSize: 12.5, color: colors.textMuted, fontStyle: 'italic' },
  acItem: { paddingVertical: spacing.sm, paddingHorizontal: spacing.sm, borderBottomWidth: 1, borderBottomColor: colors.border },
  acItemText: { fontSize: 13.5, color: colors.text },
  actions: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.sm },
  ghostBtn: { paddingVertical: spacing.sm + 2, paddingHorizontal: spacing.md, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border, alignItems: 'center', justifyContent: 'center' },
  ghostBtnText: { fontSize: 14, fontWeight: '700', color: colors.textMuted },
  primaryBtn: { flex: 1, paddingVertical: spacing.sm + 2, borderRadius: radii.sm, backgroundColor: colors.primary, alignItems: 'center', justifyContent: 'center' },
  primaryBtnText: { color: '#fff', fontWeight: '700', fontSize: 14 },
  modalBackdrop: { flex: 1, backgroundColor: 'rgba(20,20,26,0.4)', justifyContent: 'center', padding: spacing.lg },
  modalSheet: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.sm },
  modalTitle: { fontSize: 13, fontWeight: '800', color: colors.textMuted, padding: spacing.sm },
  modalOption: { paddingVertical: spacing.sm + 2, paddingHorizontal: spacing.sm },
  modalOptionText: { fontSize: 15, color: colors.text },
});
