import { Text, TextField, TextFieldRef, View } from "react-native-ui-lib";
import React, { useEffect, useRef } from "react";
import { GroceryCategory, useGroceryContext } from "@/contexts/GroceryContext";
import { Dropdown } from "react-native-element-dropdown";
import CloseXIcon from "@/assets/svgs/CloseXIcon";
import { findNodeHandle, StyleSheet, UIManager } from "react-native";
import DropdownIcon from "@/assets/svgs/DropdownIcon";
import { AntDesign } from "@expo/vector-icons";

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

const EditGroceryItem = ({
  editGrocery,
  onInputFocus,
}: {
  editGrocery: IEditGrocery;
  onInputFocus: (y: number) => void;
}) => {
  const { fuzzyMatchGroceryCategory } = useGroceryContext();
  const inputRef = useRef<TextFieldRef>(null);
  const containerRef = useRef(null);

  const handleFocus = () => {
    if (containerRef.current) {
      const handle = findNodeHandle(containerRef.current);
      if (handle) {
        UIManager.measure(
          handle,
          (
            x: number,
            y: number,
            width: number,
            height: number,
            pageX: number,
            pageY: number
          ) => {
            onInputFocus(pageY);
          }
        );
      }
    }
  };

  const groceryCategoryOptions = Object.values(GroceryCategory).map(
    (category) => ({
      label: category,
      value: category,
    })
  );

  const handleSubmit = () => {
    inputRef?.current?.blur();
    if (editGrocery.setSubmit) {
      editGrocery.setSubmit(true);
    }
    if (editGrocery.handleEditSubmit) {
      editGrocery.handleEditSubmit({
        id: editGrocery.id,
        title: editGrocery.title,
        category: editGrocery.category,
      });
    }
    if (editGrocery.closeEdit) {
      editGrocery.closeEdit();
    }
  };

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }

    console.log(editGrocery.category);
  }, []);

  return (
    <View
      ref={containerRef}
      style={{
        backgroundColor: "white",
        width: "100%",
        borderRadius: 25,
        paddingHorizontal: 13,
        paddingVertical: 10,
        marginTop: 0,
      }}
    >
      <View row spread centerV>
        <TextField
          text70T
          ref={inputRef}
          onFocus={handleFocus}
          placeholder="Grocery"
          value={editGrocery.title}
          onSubmitEditing={handleSubmit}
          numberOfLines={1}
          returnKeyType="done"
          onChangeText={(value) => {
            editGrocery.setTitle(value);
            let groceryCategory = fuzzyMatchGroceryCategory(value);
            if (editGrocery.setCategory) {
              editGrocery.setCategory(groceryCategory);
            }
          }}
          maxLength={25}
        />
        <View row centerV>
          <AntDesign
            name="check"
            size={24}
            style={{
              color: "green",
              marginRight: 15,
            }}
            onPress={handleSubmit}
          />
          <CloseXIcon
            onPress={() => {
              if (editGrocery.closeEdit) {
                editGrocery.closeEdit();
              }
            }}
          />
        </View>
      </View>
      <Dropdown
        style={{ marginTop: 15 }}
        data={groceryCategoryOptions}
        placeholder="Select grocery category"
        placeholderStyle={{
          color: "#a2a2a2",
          fontFamily: "Manrope_500Medium",
          fontSize: 13.2,
        }}
        labelField="label"
        valueField="value"
        value={editGrocery.category}
        iconColor="white"
        activeColor={"#fd1775"}
        containerStyle={styles.dropdownStyle}
        itemTextStyle={styles.itemText}
        itemContainerStyle={styles.itemStyle}
        selectedTextStyle={styles.selectedText}
        renderLeftIcon={() => (
          <DropdownIcon
            style={{ marginRight: 8 }}
            color={
              editGrocery.category == GroceryCategory.None
                ? "#7b7b7b"
                : "#fd1775"
            }
          />
        )}
        renderItem={(item) => {
          return (
            <View height={36.02} centerV>
              <Text style={styles.itemText}>{item.label}</Text>
            </View>
          );
        }}
        onChange={(item) => {
          if (editGrocery.handleEditSubmit) {
            editGrocery.handleEditSubmit({
              id: editGrocery.id,
              category: item.value,
            });
            if (editGrocery.closeEdit) editGrocery.closeEdit();
          } else {
            if (editGrocery.setCategory) {
              editGrocery.setCategory(item.value);
            }
          }
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  itemText: {
    fontFamily: "Manrope_400Regular",
    fontSize: 15.42,
    paddingLeft: 15,
  },
  selectedText: {
    fontFamily: "Manrope_500Medium",
    fontSize: 13.2,
    color: "#fd1775",
  },
  dropdownStyle: { borderRadius: 6.61, height: 115.34, width: 187 },
  itemStyle: { padding: 0, margin: 0 },
});

export default EditGroceryItem;
