import {Text, View} from "react-native";
import React, {useEffect, useRef} from "react";
import {TextField, TextFieldRef} from "react-native-ui-lib";
import {GroceryCategory, useGroceryContext,} from "@/contexts/GroceryContext";

interface IEditGrocery {
    id?: string;
    title: string;
    category: GroceryCategory;
    setTitle: (value: string) => void;
    setCategory?: (category: GroceryCategory) => void;
    setSubmit?: (value: boolean) => void;
    closeEdit?: (value: boolean) => void;
    handleEditSubmit?: Function
}

const EditGroceryItem = ({editGrocery}: { editGrocery: IEditGrocery }) => {
    const {fuzzyMatchGroceryCategory} = useGroceryContext();
    const inputRef = useRef<TextFieldRef>(null);

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

    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.focus(); // Focus on the TextField
        }
    }, []);

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

export default EditGroceryItem;
