import { useEffect, useRef, useState } from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import { suggestIngredientNames } from '../../../api/foodSearch';
import { colors, spacing, radii, typography } from '../../../theme';

type Props = {
  values: string[];
  onChange: (values: string[]) => void;
};

export function ExcludedIngredientsField({ values, onChange }: Props) {
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (debounceTimer.current) clearTimeout(debounceTimer.current);

    if (query.trim().length < 2) {
      setSuggestions([]);
      return;
    }

    debounceTimer.current = setTimeout(async () => {
      const result = await suggestIngredientNames(query.trim());
      setSuggestions([...new Set([...result.ingredients, ...result.ciqual])].slice(0, 8));
    }, 250);

    return () => { if (debounceTimer.current) clearTimeout(debounceTimer.current); };
  }, [query]);

  function addValue(name: string) {
    const trimmed = name.trim();
    if (trimmed === '' || values.some((v) => v.toLowerCase() === trimmed.toLowerCase())) return;
    onChange([...values, trimmed]);
    setQuery('');
    setSuggestions([]);
  }

  function removeValue(name: string) {
    onChange(values.filter((v) => v !== name));
  }

  return (
    <View style={styles.container}>
      {values.length > 0 ? (
        <View style={styles.chips}>
          {values.map((value) => (
            <Pressable key={value} style={styles.chip} onPress={() => removeValue(value)}>
              <Text style={styles.chipText}>{value}</Text>
              <Text style={styles.chipRemove}>✕</Text>
            </Pressable>
          ))}
        </View>
      ) : null}

      <TextInput
        style={styles.input}
        placeholder="Ex. : arachide, crevette…"
        placeholderTextColor={colors.textMuted}
        value={query}
        onChangeText={setQuery}
        onSubmitEditing={() => addValue(query)}
        autoCapitalize="none"
      />

      {suggestions.length > 0 ? (
        <View style={styles.suggestions}>
          {suggestions.map((suggestion) => (
            <Pressable key={suggestion} style={styles.suggestion} onPress={() => addValue(suggestion)}>
              <Text style={styles.suggestionText}>{suggestion}</Text>
            </Pressable>
          ))}
        </View>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: spacing.sm },
  chips: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs },
  chip: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    backgroundColor: colors.surface,
    borderRadius: radii.pill,
    paddingHorizontal: spacing.sm,
    paddingVertical: 6,
  },
  chipText: { ...typography.caption, fontSize: 13, color: colors.text, fontWeight: '600' },
  chipRemove: { color: colors.textMuted, fontSize: 12 },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    color: colors.text,
  },
  suggestions: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    overflow: 'hidden',
  },
  suggestion: { paddingHorizontal: spacing.sm, paddingVertical: spacing.sm, borderBottomWidth: 1, borderBottomColor: colors.border },
  suggestionText: { ...typography.body, fontSize: 14, color: colors.text },
});
