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 {ImageBackground, 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";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";

const GroceryItem = ({
  item,
  handleItemApproved,
}: {
  item: IGrocery;
  handleItemApproved: (id: string, changes: Partial<IGrocery>) => void;
}) => {
  const { updateGroceryItem } = useGroceryContext();
  const { profileData } = useAuthContext();
  const isParent = profileData?.userType === ProfileType.PARENT;

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

  const closeEdit = () => {
    setIsEditingTitle(false);
  }

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

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

  useEffect(() => {
    console.log(item);
    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);
      }
    }
  };

  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0)}`;
  };

  return (
    <View
      key={item.id}
      style={{
        borderRadius: 17,
        marginVertical: 5,
        paddingHorizontal: isEditingTitle ? 0 : 13,
        paddingVertical: isEditingTitle ? 0 : 10,
      }}
      backgroundColor="white"
      centerV
    >
      <View row spread>
        <EditGroceryFrequency
          visible={openFreqEdit}
          key={item.id}
          item={item}
          onClose={() => {
            setOpenFreqEdit(false);
          }}
        />
        {isEditingTitle ?
            <EditGroceryItem
              editGrocery={{
                id: item.id,
                title: newTitle,
                category: category,
                setTitle: setNewTitle,
                setCategory: setCategory,
                closeEdit: closeEdit,
                handleEditSubmit: updateGroceryItem,
              }}
            /> :
            <View>
              {isParent ?
                <TouchableOpacity onPress={() => setIsEditingTitle(true)}>
                  <Text text70T black style={styles.title}>
                    {item.title}
                  </Text>
                </TouchableOpacity> :
                <Text text70T black style={styles.title}>
                  {item.title}
                </Text>
              }
            </View>
        }
        {!item.approved ? (
          <View row centerV marginB-10>
            {isParent &&
                <>
                  <AntDesign
                    name="check"
                    size={24}
                    style={{
                      color: "green",
                      marginRight: 15,
                    }}
                    onPress={isParent ? () => handleItemApproved(item.id, { approved: true }) : null}
                  />
                  <AntDesign
                    name="close"
                    size={24}
                    style={{ color: "red" }}
                    onPress={isParent ? () => handleItemApproved(item.id, { approved: false }) : null}
                  />
                </>}
          </View>
        ) : (
          !isEditingTitle && isParent && (
            <Checkbox
              value={item.bought}
              containerStyle={[styles.checkbox, {borderRadius: 50}]}
              style={styles.checked}
              borderRadius={50}
              color="#fd1575"
              hitSlop={20}
              onValueChange={() =>
                updateGroceryItem({ id: item.id, bought: !item.bought })
              }
            />
          )
        )}
      </View>
      {!item.approved && (
        <View>
          <View centerH>
            <View height={0.7} backgroundColor="#e7e7e7" width={"98%"} />
          </View>
          <View paddingL-0 paddingT-12 flexS row centerV>
            {profileData?.pfp ?  <ImageBackground
                source={require("../../../assets/images/child-picture.png")}
                style={{
                  height: 24.64,
                  aspectRatio: 1,
                  borderRadius: 22,
                  overflow: "hidden",
                }}
            /> :
              <View
                style={{
                  position: "relative",
                  width: 24.64,
                  aspectRatio: 1,
                  marginRight: 4
                }}
              >
              <View
                  style={{
                    backgroundColor: "#ccc",
                    justifyContent: "center",
                    alignItems: "center",
                    borderRadius: 100, // Circular shape
                    width: "100%",
                    height: "100%",
                  }}
              >
                <Text
                  style={{
                    color: "#fff",
                    fontSize: 12,
                    fontWeight: "bold",
                  }}
                >
                  {itemCreator ? getInitials(itemCreator.firstName, itemCreator.lastName) : ""}
                </Text>
              </View>
            </View>}
            <Text color="#858585" style={styles.authorTxt}>
              Requested by {itemCreator?.firstName}
            </Text>
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  authorTxt: { fontFamily: "Manrope_500Medium", fontSize: 12 },
  checkbox: {
    borderRadius: 50,
    borderWidth: 0.7,
    color: "#bfbfbf",
    borderColor: "#bfbfbf",
    width: 24.64,
    aspectRatio: 1,
  },
  title: {
    fontFamily: "Manrope_500Medium",
    fontSize: 15,
  },
  checked: {
    borderRadius: 50,
  },
});

export default GroceryItem;
