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

export type AnchorFoodSelection = { label: string; recipeId?: number; ciqualName?: string };

type Props = {
  value: AnchorFoodSelection | null;
  onChange: (selection: AnchorFoodSelection | null) => void;
};

type Group = { title: string; items: { label: string; selection: AnchorFoodSelection }[] };

export function AnchorFoodSearchField({ value, onChange }: Props) {
  const [query, setQuery] = useState(value?.label ?? '');
  const [groups, setGroups] = useState<Group[]>([]);
  const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

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

    if (query.trim().length < 2 || query === value?.label) {
      setGroups([]);
      return;
    }

    debounceTimer.current = setTimeout(async () => {
      const result = await suggestFood(query.trim());
      const next: Group[] = [];
      if (result.mine.length > 0) {
        next.push({ title: 'Mes recettes', items: result.mine.map((r) => ({ label: r.name, selection: { label: r.name, recipeId: r.id } })) });
      }
      if (result.all.length > 0) {
        next.push({ title: 'Autres recettes', items: result.all.map((r) => ({ label: r.name, selection: { label: r.name, recipeId: r.id } })) });
      }
      const foods = [...result.ingredients, ...result.ciqual];
      if (foods.length > 0) {
        next.push({ title: 'Aliments', items: foods.map((f) => ({ label: f.name, selection: { label: f.name, ciqualName: f.name } })) });
      }
      setGroups(next);
    }, 250);

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

  function select(selection: AnchorFoodSelection) {
    onChange(selection);
    setQuery(selection.label);
    setGroups([]);
  }

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Chercher une recette ou un aliment…"
        placeholderTextColor={colors.textMuted}
        value={query}
        onChangeText={(text) => {
          setQuery(text);
          if (value !== null) onChange(null);
        }}
        autoCapitalize="none"
      />

      {groups.length > 0 ? (
        <View style={styles.suggestions}>
          {groups.map((group) => (
            <View key={group.title}>
              <Text style={styles.groupTitle}>{group.title}</Text>
              {group.items.map((item) => (
                <Pressable key={`${group.title}-${item.label}`} style={styles.suggestion} onPress={() => select(item.selection)}>
                  <Text style={styles.suggestionText}>{item.label}</Text>
                </Pressable>
              ))}
            </View>
          ))}
        </View>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: spacing.sm },
  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',
  },
  groupTitle: {
    ...typography.caption,
    fontSize: 11,
    fontWeight: '700',
    color: colors.textMuted,
    textTransform: 'uppercase',
    paddingHorizontal: spacing.sm,
    paddingTop: spacing.xs,
  },
  suggestion: { paddingHorizontal: spacing.sm, paddingVertical: spacing.sm, borderBottomWidth: 1, borderBottomColor: colors.border },
  suggestionText: { ...typography.body, fontSize: 14, color: colors.text },
});
