import { View, Text } from "react-native";
import React, { useEffect, useState } from "react";
import { TextField } from "react-native-ui-lib";
import {
  GroceryCategory,
  IGrocery,
  useGroceryContext,
} from "@/contexts/GroceryContext";
import { TouchableWithoutFeedback } from "react-native-gesture-handler";

interface IEditGrocery {
  id?: number;
  title: string;
  setTitle: (value: string) => void;
  setCategory?: (category: GroceryCategory) => void;
  category: GroceryCategory;
  setSubmit?: (value: boolean) => void;
  updateCategory?: (id: number, changes: Partial<IGrocery>) => void;
  closeEdit?: (value: boolean) => void;
}

const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
  const { fuzzyMatchGroceryCategory } = useGroceryContext();

  useEffect(() => {
    if (editGrocery.setCategory)
      editGrocery.setCategory(fuzzyMatchGroceryCategory(editGrocery.title));
  }, [editGrocery.title]);

  return (
      <View
        style={{
          backgroundColor: "white",
          width: "100%",
          borderRadius: 25,
          padding: 15,
        }}
      >
        <TextField
          placeholder="Grocery"
          value={editGrocery.title}
          onChangeText={(value) => {
            editGrocery.setTitle(value);
          }}
          onSubmitEditing={() => {
            if (editGrocery.setSubmit) editGrocery.setSubmit(true);
            if (editGrocery.closeEdit) editGrocery.closeEdit(false);
            if (editGrocery.updateCategory && editGrocery.id)
              editGrocery.updateCategory(editGrocery.id, {
                category: fuzzyMatchGroceryCategory(editGrocery.title), title: editGrocery.title
              });
          }}
          maxLength={25}
        />
        <Text>{editGrocery.category}</Text>
      </View>
  );
};

export default EditGroceryItem;
