import {Checkbox, Text, TouchableOpacity, View,} from "react-native-ui-lib";
import React, {useEffect, useState} from "react";
import {AntDesign} from "@expo/vector-icons";
import {GroceryCategory, useGroceryContext,} from "@/contexts/GroceryContext";
import EditGroceryFrequency from "./EditGroceryFrequency";
import EditGroceryItem from "./EditGroceryItem";
import {StyleSheet} from "react-native";
import {IGrocery} from "@/hooks/firebase/types/groceryData";
import firestore from "@react-native-firebase/firestore";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";

const GroceryItem = ({
  item,
  handleItemApproved,
}: {
  item: IGrocery;
  handleItemApproved: (id: string, changes: Partial<IGrocery>) => void;
}) => {
  const { updateGroceryItem } = useGroceryContext();

  const [openFreqEdit, setOpenFreqEdit] = useState<boolean>(false);
  const [isEditingTitle, setIsEditingTitle] = useState<boolean>(false);
  const [newTitle, setNewTitle] = useState<string>("");
  const [category, setCategory] = useState<GroceryCategory>(
    GroceryCategory.None
  );
  const [itemCreator, setItemCreator] = useState<UserProfile>(null);

  const handleTitleChange = (newTitle: string) => {
    updateGroceryItem({id: item?.id, title: newTitle});
  };

  const handleCategoryChange = (newCategory: GroceryCategory) => {
    updateGroceryItem({id: item?.id, category: newCategory});
  };

  useEffect(() => {
    setNewTitle(item.title);

    getItemCreator(item?.creatorId);
  }, []);

  const getItemCreator = async (uid: string | undefined) => {
    if (uid) {
      const documentSnapshot = await firestore()
          .collection("Profiles")
          .doc(uid)
          .get();

      if (documentSnapshot.exists) {
        setItemCreator(documentSnapshot.data() as UserProfile)
      }
    }
  }

  return (
    <View
      key={item.id}
      style={{ borderRadius: 18, marginVertical: 5 }}
      backgroundColor="white"
      centerV
      paddingV-12
      paddingR-12
      paddingL-12
    >
      <View row spread>
        <EditGroceryFrequency
          visible={openFreqEdit}
          key={item.id}
          item={item}
          onClose={() => {
            setOpenFreqEdit(false);
          }}
        />
        {!isEditingTitle ? (
          <View>
            <TouchableOpacity onPress={() => setIsEditingTitle(true)}>
              <Text text70T>{item.title}</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <EditGroceryItem
            editGrocery={{
              id: item.id,
              title: newTitle,
              setTitle: setNewTitle,
              category: category,
              updateCategory: updateGroceryItem,
              closeEdit: setIsEditingTitle,
              setCategory: setCategory,
            }}
          />
        )}
        {!item.approved ? (
          <View row centerV marginB-10>
            <AntDesign
              name="check"
              size={24}
              style={{
                color: item.approved ? "green" : "#aaaaaa",
                marginRight: 15
              }}
              onPress={() => {
                handleItemApproved(item.id, { approved: true });
              }}
            />
            <AntDesign
              name="close"
              size={24}
              style={{ color: item.approved ? "#aaaaaa" : "red" }}
              onPress={() => {
                handleItemApproved(item.id, { approved: false });
              }}
            />
          </View>
        ) : (
          <Checkbox
            value={item.bought}
            containerStyle={styles.checkbox}
            hitSlop={20}
            onValueChange={() =>
              updateGroceryItem({ id: item.id, bought: !item.bought })
            }
          />
        )}
      </View>
      {!item.approved && (
        <View>
          <View centerH>
            <View height={1} backgroundColor="#e7e7e7" width={"90%"} />
          </View>
          <View paddingL-0 paddingT-10 flexS row centerV>
            <View
              style={{
                width: 25,
                aspectRatio: 1,
                borderRadius: 50,
                backgroundColor: "red",
                marginRight: 10,
              }}
            ></View>
            <Text color="#858585" text70>
              Requested by {itemCreator?.firstName}
            </Text>
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  checkbox: {
    borderRadius: 50,
    borderWidth: 1,
    color: "#bfbfbf",
    borderColor: "#bfbfbf",
    width: 28,
    aspectRatio: 1,
  },
});

export default GroceryItem;
