import React, { useEffect, useState } from "react";
import {
  Dimensions,
  Image,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import {
  faCartShopping,
  faMinus,
  faPlus,
  faStore,
} from "@fortawesome/free-solid-svg-icons";
import {
  faBell,
  faComment,
  faComments,
  faUserCircle,
} from "@fortawesome/free-regular-svg-icons";
import Modal from "react-native-modal";

import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation } from "@react-navigation/native";
import {
  create_order,
  get_order,
  get_orders_by_customer,
  update_order,
  update_order_item,
} from "../../services/api/controllers/order";
// import { user } from "../../constants/user";
import { get_vendor } from "../../services/api/controllers/vendor";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";
import CheckOutModal from "./CheckOutModal";

const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").width;

const BottomNav = ({
  settabActive,
  activeTab,
  setcartList,
  cartList,
  product,
  activeVar,
  setModalVisible,
}) => {
  const navigation = useNavigation();
  const [inputValue, setInputValue] = useState("1");
  const [orderId, setorderId] = useState("");
  const [order, setorder] = useState([]);
  const [orders, setorders] = useState([]);
  const [orderExist, setorderExist] = useState(false);
  const [orderIdE, setorderIdE] = useState(false);
  const [orderE, setorderE] = useState(false);
  const [token, settoken] = useState("");

  const [itemId, setitemId] = useState(false);
  const [refresh, setrefresh] = useState(false);
  const [minLimit, setminLimit] = useState(null);
  const [isminLimit, setisminLimit] = useState(false);
  const [maxLimit, setmaxLimit] = useState(null);
  const [ismaxLimit, setismaxLimit] = useState(false);

  const [vendorName, setvendorName] = useState("");
  const toast = useToast();
  // console.log(product._id);
  useEffect(() => {
    if (product) {
      console.log(" this product min order is" + product?.minimum_order);
      if (product?.minimum_order) {
        setisminLimit(true);
        setminLimit(product?.minimum_order);
        setInputValue(product?.minimum_order);
      } else {
        setisminLimit(false);
      }
      if (product?.stock) {
        setismaxLimit(true);
        setmaxLimit(product?.stock);
        // setInputValue(product?.minimum_order);
      } else {
        setisminLimit(false);
      }
    }
  }, [product]);

  console.log("---------------" + orderExist + "-----" + orderIdE);

  useEffect(() => {
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          settoken(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    get_vendor({
      id: product.vendor_api_id,
    })
      .then((result) => {
        console.log("successful get vendor name" + result.data.user_login);
        if (result.status === 200) {
          setvendorName(result.data.user_login);
        }
      })
      .catch((err) => {
        console.error(err);
      });
    if (product) {
      console.log(" this product min order is" + product?.minimum_order);
      if (product?.minimum_order) {
        setisminLimit(true);
        setminLimit(product?.minimum_order);
        setInputValue(product?.minimum_order);
      }
      if (product?.stock) {
        setismaxLimit(true);
        setmaxLimit(product?.stock);
        // setInputValue(product?.minimum_order);
      } else {
        setisminLimit(false);
      }
    }
  }, []);

  useEffect(() => {
    if (refresh === true) {
      get_orders_by_customer({ id: user[0]._id })
        .then((result) => {
          console.log("successful get order" + result.status);
          findOrderIdByProductId(result.data, product?._id);

          setorders(result.data);
          setrefresh(false);
        })
        .catch((err) => {
          console.error(err);
        });
    }
  }, [refresh]);

  useEffect(() => {
    // if (refresh === true) {
    // get_orders_by_customer({ id: user[0]._id })
    //   .then((result) => {
    //     console.log("successful get order" + result.status);
    console.log(product._id + "-------------------------");
    findOrderIdByProductId(orders, product?._id);

    //   setorders(result.data);
    //   setrefresh(false);
    // })
    // .catch((err) => {
    //   console.error(err);
    // });
    // }
  }, [product]);
  const [user, setuser] = useState([]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        get_orders_by_customer({ id: userDataArray[0]._id })
          .then((result) => {
            console.log("successful get order" + result.status);
            findOrderIdByProductId(result.data, product?._id);

            setorders(result.data);
          })
          .catch((err) => {
            console.error(err);
          });
        console.log(pass);
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  // Function to handle text input change
  const handleTextChange = (text) => {
    // Use a regular expression to allow only numeric characters
    const numericValue = text.replace(/[^0-9]/g, "");
    if (!isminLimit || !ismaxLimit) {
      setInputValue(parseInt(numericValue));
    } else {
      if (parseInt(numericValue) < parseInt(minLimit)) {
        toast.show(`The minimum order for this product is ${minLimit}!`, {
          type: "danger",
          placement: "top",
          duration: 4000,
          offset: 30,
          animationType: "slide-in",
        });
        setInputValue(parseInt(minLimit));
      } else if (parseInt(numericValue) > parseInt(maxLimit)) {
        toast.show(`The maximum order for this product is ${maxLimit}!`, {
          type: "danger",
          placement: "top",
          duration: 4000,
          offset: 30,
          animationType: "slide-in",
        });
        setInputValue(parseInt(minLimit));
      } else {
        setInputValue(parseInt(numericValue));
      }
    }
  };
  const handleInputChange = (text) => {
    if (!isminLimit || !ismaxLimit) {
      if (text === "add") {
        setInputValue((parseInt(inputValue, 10) + 1).toString()); // Parse to integer and convert back to string
      } else if (text === "minus") {
        const newValue = parseInt(inputValue, 10) - 1;
        setInputValue(newValue >= 1 ? newValue.toString() : 1); // Ensure it's not less than 1
      }
    } else {
      if (text === "add") {
        const newValue = parseInt(inputValue, 10) + 1;

        if (parseInt(newValue) > parseInt(maxLimit)) {
          toast.show(`The maximum order for this product is ${maxLimit}!`, {
            type: "danger",
            placement: "top",
            duration: 4000,
            offset: 30,
            animationType: "slide-in",
          });
        } else {
          setInputValue((parseInt(inputValue, 10) + 1).toString()); // Parse to integer and convert back to string
        }
      } else if (text === "minus") {
        const newValue = parseInt(inputValue, 10) - 1;
        if (parseInt(newValue) < parseInt(minLimit)) {
          toast.show(`The minimum order for this product is ${minLimit}!`, {
            type: "danger",
            placement: "top",
            duration: 4000,
            offset: 30,
            animationType: "slide-in",
          });
        } else {
          setInputValue(newValue >= 1 ? newValue.toString() : 1); // Ensure it's not less than 1
        }
      }
    }
  };

  const tabSwitch = (e) => {
    settabActive(e);
  };
  function findOrderIdByProductId(orders, productIdToFind) {
    console.log("checking product on cart" + productIdToFind);
    const sortOrder =
      orders?.filter(
        (item) => item.status === "CART" || item.status === "Cart"
      ) ?? [];
    for (const order of sortOrder) {
      console.log("orders checking");
      const orderIdd = order._id;
      const item = order.items.find(
        (item) => item.product.product_id === productIdToFind
      );
      if (item) {
        setitemId(item._id);
        // console.log(order._id + "+" + item.product.product_id);
        setorderE(order);
        setorderIdE(orderIdd);
        setorderExist(true);
        console.log(
          "---------------" + orderExist + "-----" + orderIdE + "--------2"
        );

        console.log("found it");
      }
    }
    return null; // Return null if the product_id is not found in any item
  }

  const addToCart = () => {
    // Create a copy of the current cartList
    // const updatedCart = [...cartList];

    // // Modify the product object to include inputValue and variation
    // const modifiedProduct = {
    //   ...product,
    //   quantity: parseInt(inputValue),
    //   variation: "blue",
    // };

    // // Add the modified product to the updatedCart array
    // updatedCart.push(modifiedProduct);

    // // Update the cartList state with the new cart array
    // setcartList(updatedCart);
    // console.log(orderExist + orderIdE + itemId);
    console.log(product?.product_type);

    if (product.product_type === "variable") {
      console.log("variable");

      if (!activeVar || activeVar === null) {
        toast.show("Select variation first!", {
          type: "danger",
          placement: "top",
          duration: 4000,
          offset: 30,
          animationType: "slide-in",
        });
      }
    } else if (product.product_type === "variation") {
      console.log("variation");

      // function checkVariantValue(variantsArray) {
      //   let variants = "";
      //   if (variantsArray.length > 0) {
      //     const variant = variantsArray[0]; // Accessing the first element in the variants array
      //     for (let key in variant) {
      //       // if (key !== "_id" && variant[key] !== null && variant[key] !== "") {

      //       // }
      //       variants === variants + "eyy";
      //     }
      //   }
      //   return variants; // Returning null if no non-empty value is found
      // }
      // const result = checkVariantValue(product.variants);
      // console.log(
      //   result + "------------------------------------------------------------"
      // );
      // console.log(product.variants);
      AsyncStorage.getItem("AccessToken")
        .then((pass) => {
          console.log(pass);
          if (pass !== null) {
            if (orderExist) {
              const quan = orderE.items[0].quantity;
              console.log(quan);
              const quanti = parseInt(quan) + parseInt(inputValue);
              console.log("final: " + quanti);

              update_order_item({
                token: token,
                orderId: orderIdE,
                itemId: itemId,
                body: {
                  quantity: quanti.toString(),
                },
              })
                .then((result) => {
                  // console.log("successful tran" + result);
                  if (result.status === 200) {
                    // setInputValue(quan.toString()); // Parse to integer and convert back to string
                    update_order({
            token: token,

                      id: orderIdE,
                      body: {
                        total_amount: orderE.items[0].price * quanti,
                      },
                    })
                      .then((results) => {
                        if (results.status === 200) {
                          console.log("price: " + results.data.total_amount);
                          toast.show("Added to Cart!", {
                            type: "success",
                            placement: "top",
                            duration: 2000,
                            offset: 30,
                            animationType: "slide-in",
                          });
                          setrefresh(true);
                        } else {
                          console.log("update order failed");
                        }
                      })
                      .catch((err) => {
                        console.error(err);
                      });
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
            } else if (orderExist === false) {
              create_order({
                token,
                token,

                body: {
                  customer: {
                    customer_id: user[0]?._id,
                    name: user[0]?.first_name + " " + user[0]?.last_name,
                  },
                  // order_date: "2023/09/27",
                  total_amount:
                    product.sale_price ??
                    product.regular_price * parseFloat(inputValue),
                  items: [
                    {
                      product: {
                        product_image: product.product_image,
                        product_id: product._id,
                        name: product.product_name,
                      },
                      price: product.sale_price ?? product.regular_price,
                      quantity: inputValue,
                      vendor_id: product.vendor_api_id,
                      vendor_name: vendorName,
                    },
                  ],
                  status: "CART",
                  shipping_fee: product.shipping_fee
                    ? product.shipping_fee
                    : 50,
                },
              })
                .then((result) => {
                  console.log("successful add to cart" + result.status);
                  setrefresh(true);

                  toast.show("Added to Cart!", {
                    type: "success",
                    placement: "top",
                    duration: 4000,
                    offset: 30,
                    animationType: "slide-in",
                  });
                })
                .catch((err) => {
                  console.error(err);
                });
            }
          } else {
            navigation.navigate("Login");
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
    } else {
      console.log("simple");
      AsyncStorage.getItem("AccessToken")
        .then((pass) => {
          console.log(pass);
          if (pass !== null) {
            if (orderExist) {
              const quan = orderE.items[0].quantity;
              console.log(quan);
              const quanti = parseInt(quan) + parseInt(inputValue);
              console.log("final: " + quanti);

              update_order_item({
                token: token,
                orderId: orderIdE,
                itemId: itemId,
                body: {
                  quantity: quanti.toString(),
                },
              })
                .then((result) => {
                  // console.log("successful tran" + result);
                  if (result.status === 200) {
                    // setInputValue(quan.toString()); // Parse to integer and convert back to string
                    update_order({
            token: token,

                      id: orderIdE,
                      body: {
                        total_amount: orderE.items[0].price * quanti,
                      },
                    })
                      .then((results) => {
                        if (results.status === 200) {
                          console.log("price: " + results.data.total_amount);
                          toast.show("Added to Cart!", {
                            type: "success",
                            placement: "top",
                            duration: 2000,
                            offset: 30,
                            animationType: "slide-in",
                          });
                          setrefresh(true);
                        } else {
                          console.log("update order failed");
                        }
                      })
                      .catch((err) => {
                        console.error(err);
                      });
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
            } else if (orderExist === false) {
              create_order({
                token,
                token,

                body: {
                  customer: {
                    customer_id: user[0]?._id,
                    name: user[0]?.first_name + " " + user[0]?.last_name,
                  },
                  // order_date: "2023/09/27",
                  total_amount:
                    product.sale_price ??
                    product.regular_price * parseFloat(inputValue),
                  items: [
                    {
                      product: {
                        product_image: product.product_image,
                        product_id: product._id,
                        name: product.product_name,
                      },
                      price: product.sale_price ?? product.regular_price,
                      quantity: inputValue,
                      vendor_id: product.vendor_api_id,
                      vendor_name: vendorName,
                    },
                  ],
                  status: "CART",
                  shipping_fee: product.shipping_fee
                    ? product.shipping_fee
                    : 50,
                },
              })
                .then((result) => {
                  console.log("successful add to cart" + result.status);
                  setrefresh(true);

                  toast.show("Added to Cart!", {
                    type: "success",
                    placement: "top",
                    duration: 4000,
                    offset: 30,
                    animationType: "slide-in",
                  });
                })
                .catch((err) => {
                  console.error(err);
                });
            }
          } else {
            navigation.navigate("Login");
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
        });
    }
  };
  const checkOut = () => {
    /* ---------------Check for the user saved email--------------- */
    if (product.product_type === "variable") {
      if (!activeVar || activeVar === null) {
        toast.show("Select variation first!", {
          type: "danger",
          placement: "top",
          duration: 4000,
          offset: 30,
          animationType: "slide-in",
        });
      } else {
        AsyncStorage.getItem("AccessToken")
          .then((pass) => {
            console.log("checkout " + pass);
            if (pass === null) {
              navigation.navigate("Login");
            } else if (pass !== null) {
              create_order({
                token: token,
                body: {
                  customer: {
                    customer_id: user[0]?._id,
                    name: user[0]?.first_name + " " + user[0]?.last_name,
                    product_image: product.product_image,
                  },
                  // order_date: "2023/09/27",
                  total_amount:
                    product.sale_price ??
                    product.regular_price * parseFloat(inputValue),
                  items: [
                    {
                      product: {
                        product_image: product.product_image,
                        product_id: product._id,
                        name: product.product_name,
                      },
                      price: product.sale_price ?? product.regular_price,
                      quantity: inputValue,
                      vendor_id: product.vendor_api_id,
                      vendor_name: vendorName,
                    },
                  ],
                  status: "TO CHECKOUT",
                  shipping_fee: product.shipping_fee
                    ? product.shipping_fee
                    : 50,
                },
              })
                .then((result) => {
                  console.log("successful transaction" + result.status);
                  if (result.status === 201) {
                    // console.log(result.data)
                    setorder(result.data);
                    setorderId(result.data._id);
                    navigation.navigate("CheckOut", {
                      product: result.data,
                      orderId: result.data._id,
                    });
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
            }
          })
          .catch((error) => {
            console.log(error + "weeewwww");
            navigation.navigate("Login");
          });
      }
    } else {
      AsyncStorage.getItem("AccessToken")
        .then((pass) => {
          console.log("checkout " + pass);
          if (pass === null) {
            navigation.navigate("Login");
          } else if (pass !== null) {
            create_order({
              token,
              token,
              body: {
                customer: {
                  customer_id: user[0]?._id,
                  name: user[0]?.first_name + " " + user[0]?.last_name,
                  product_image: product.product_image,
                },
                // order_date: "2023/09/27",
                total_amount:
                  product.sale_price ??
                  product.regular_price * parseFloat(inputValue),
                items: [
                  {
                    product: {
                      product_image: product.product_image,
                      product_id: product._id,
                      name: product.product_name,
                    },
                    price: product.sale_price ?? product.regular_price,
                    quantity: inputValue,
                    vendor_id: product.vendor_api_id,
                    vendor_name: vendorName,
                  },
                ],
                status: "TO CHECKOUT",
                shipping_fee: product.shipping_fee ? product.shipping_fee : 50,
              },
            })
              .then((result) => {
                console.log("successful transaction" + result.status);
                if (result.status === 201) {
                  // console.log(result.data)
                  setorder(result.data);
                  setorderId(result.data._id);
                  navigation.navigate("CheckOut", {
                    product: result.data,
                    orderId: result.data._id,
                  });
                }
              })
              .catch((err) => {
                console.error(err);
              });
          }
        })
        .catch((error) => {
          console.log(error + "weeewwww");
          navigation.navigate("Login");
        });
    }
  };
  return (
    <View style={styles.container}>
      <View style={styles.wrapper}>
        <TouchableOpacity
          style={styles.button}
          onPress={() =>
            product.regular_price
              ? addToCart()
              : toast.show(
                  `you need to inquire the seller for the price of this product!`,
                  {
                    type: "danger",
                    placement: "top",
                    duration: 4000,
                    offset: 30,
                    animationType: "slide-in",
                  }
                )
          }
        >
          {orderExist ? (
            <FontAwesomeIcon
              icon={faCartShopping}
              color={"#FFAA00"}
              size={25}
            />
          ) : (
            <FontAwesomeIcon
              icon={faCartShopping}
              color={"#888888"}
              size={25}
            />
          )}
        </TouchableOpacity>
        <View style={styles.quantity}>
          <TouchableOpacity
            style={styles.buttonQty}
            onPress={() => handleInputChange("minus")}
          >
            <FontAwesomeIcon icon={faMinus} color={"#888888"} size={15} />
          </TouchableOpacity>
          <TextInput
            style={styles.input}
            value={inputValue}
            onChangeText={handleTextChange}
            keyboardType="numeric" // This sets the keyboard to show numeric keys
          />
          <TouchableOpacity
            style={styles.buttonQty}
            onPress={() => handleInputChange("add")}
          >
            <FontAwesomeIcon icon={faPlus} color={"#888888"} size={15} />
          </TouchableOpacity>
        </View>
        <TouchableOpacity
          style={styles.button1}
          onPress={() => {
            if (!isminLimit) {
              product.regular_price
                ? checkOut()
                : toast.show(
                    `you need to inquire the seller for the price of this product!`,
                    {
                      type: "danger",
                      placement: "top",
                      duration: 4000,
                      offset: 30,
                      animationType: "slide-in",
                    }
                  );
            } else {
              parseInt(inputValue) < parseInt(minLimit)
                ? toast.show(
                    `The minimum order for this product is ${minLimit}!`,
                    {
                      type: "danger",
                      placement: "top",
                      duration: 4000,
                      offset: 30,
                      animationType: "slide-in",
                    }
                  )
                : checkOut();
            }
          }}
        >
          <Text style={styles.button1text}>Buy Now</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    // flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    bottom: 0,
    // position: "fixed",
    // paddingVertical: 15,
    paddingBottom: 5,
    boxShadow: "0px 0px 3px 0px rgba(0, 0, 0, 0.25)",
  },
  wrapper: {
    flexDirection: "row",
    width: "100%",
    alignItems: "center",
    justifyContent: "space-around",
    margin: "auto",
    borderTopColor: "#ddd",
    paddingVertical: 5,
    paddingBottom: 10,
    borderTopWidth: 1,
  },
  button: {
    padding: 15,
  },
  button1: {
    padding: 15,
    paddingHorizontal: 50,
    backgroundColor: "#ffaa00",
    color: "#fff",
    borderRadius: 30,
  },
  button1text: {
    color: "#fff",
    fontWeight: "600",
  },
  quantity: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  buttonQty: {
    backgroundColor: "#eee",
    padding: 5,
    margin: 5,
  },
});
export default BottomNav;
