import { faMinus, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
import Checkbox from "expo-checkbox";
import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  TextInput,
} from "react-native";
import { useToast } from "react-native-toast-notifications";
import {
  update_order,
  update_order_item,
} from "../../services/api/controllers/order";
import { get_product } from "../../services/api/controllers/product";

const CartSubCard = ({
  cart,
  shopProdLike,
  index,
  shopIndex,
  quantityChange,
  q,
}) => {
  const navigation = useNavigation();

  console.log("prod" + cart?.selected);
  const [inputValue, setInputValue] = useState(cart?.items[0].quantity, 10);
  const [error, setError] = useState(false);
  const [minLimit, setminLimit] = useState(null);
  const [isminLimit, setisminLimit] = useState(false);
  const toast = useToast();
  const [maxLimit, setmaxLimit] = useState(null);
  const [ismaxLimit, setismaxLimit] = useState(false);
  const [token, settoken] = useState("");

  // useEffect(() => {
  //   quantityChange(shopIndex, index, inputValue);
  // }, [inputValue]);

  // Function to handle text input change

  useEffect(() => {
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          settoken(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    get_product({
      id: cart?.items[0]?.product?.product_id,
    })
      .then((result1) => {
        //  console.log("result" + result);

        if (result1.error) {
          setError(result1.error);
        } else {
          // setcart(result.data);
          console.log(result1?.data);
          setisminLimit(true);
          setminLimit(
            result1?.data?.minimum_order !== ""
              ? result1.data.minimum_order
              : "1"
          );
          setismaxLimit(true);
          setmaxLimit(result1?.data?.stock !== "" ? result1.data.stock : "");
          // if (result1.data.minimum_order !== "") {
          //   setInputValue(parseInt(result1.data.minimum_order));
          // }
        }
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        // set
      });
  }, []);

  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(maxLimit));
      } else {
        setInputValue(parseInt(numericValue));
      }
    }
  };
  const handleInputChange = (text) => {
    quantityChange(!q);

    if (text === "add") {
      const quan = parseInt(inputValue) + 1;
      if (!isminLimit) {
        update_order_item({
          token: token,
          orderId: cart._id,
          itemId: cart.items[0]._id,
          body: {
            quantity: quan.toString(),
          },
        })
          .then((result) => {
            console.log("successful transaction" + result.status);
            if (result.status === 200) {
              setInputValue(quan.toString()); // Parse to integer and convert back to string
              update_order({
                token: token,

                id: cart._id,
                body: {
                  total_amount: cart.items[0].price * quan,
                },
              })
                .then((results) => {
                  if (results.status === 200) {
                    console.log("price: " + results.data.total_amount);
                  } else {
                    console.log("update order failed");
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
            }
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        if (parseInt(quan) > parseInt(maxLimit)) {
          toast.show(`The maximum order for this product is ${maxLimit}!`, {
            type: "danger",
            placement: "top",
            duration: 4000,
            offset: 30,
            animationType: "slide-in",
          });
        } else {
          update_order_item({
            token: token,

            orderId: cart._id,
            itemId: cart.items[0]._id,
            body: {
              quantity: quan.toString(),
            },
          })
            .then((result) => {
              console.log("successful transaction" + result.status);
              if (result.status === 200) {
                setInputValue(quan.toString()); // Parse to integer and convert back to string
                update_order({
                  token: token,

                  id: cart._id,
                  body: {
                    total_amount: cart.items[0].price * quan,
                  },
                })
                  .then((results) => {
                    if (results.status === 200) {
                      console.log("price: " + results.data.total_amount);
                    } else {
                      console.log("update order failed");
                    }
                  })
                  .catch((err) => {
                    console.error(err);
                  });
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    } else if (text === "minus") {
      const quan2 = parseInt(inputValue) - 1;

      if (!isminLimit) {
        update_order_item({
          token: token,

          orderId: cart._id,
          itemId: cart.items[0]._id,
          body: {
            quantity: quan2.toString(),
          },
        })
          .then((result) => {
            console.log("successful transaction" + result.status);
            if (result.status === 200) {
              const newValue = quan2;
              update_order({
                token: token,

                id: cart._id,
                body: {
                  total_amount: cart.items[0].price * quan2,
                },
              })
                .then((results) => {
                  if (results.status === 200) {
                    console.log("price: " + results.data.total_amount);
                  } else {
                    console.log("update order failed");
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
              setInputValue(newValue >= 1 ? newValue.toString() : "1"); // Ensure it's not less than 1
            }
          })
          .catch((err) => {
            console.error(err);
          });
      } else {
        if (parseInt(quan2) < parseInt(minLimit)) {
          toast.show(`The minimum order for this product is ${minLimit}!`, {
            type: "danger",
            placement: "top",
            duration: 4000,
            offset: 30,
            animationType: "slide-in",
          });
        } else {
          update_order_item({
            token: token,

            orderId: cart._id,
            itemId: cart.items[0]._id,
            body: {
              quantity: quan2.toString(),
            },
          })
            .then((result) => {
              console.log("successful transaction" + result.status);
              if (result.status === 200) {
                const newValue = quan2;
                update_order({
                  token: token,

                  id: cart._id,
                  body: {
                    total_amount: cart.items[0].price * quan2,
                  },
                })
                  .then((results) => {
                    if (results.status === 200) {
                      console.log("price: " + results.data.total_amount);
                    } else {
                      console.log("update order failed");
                    }
                  })
                  .catch((err) => {
                    console.error(err);
                  });
                setInputValue(newValue >= 1 ? newValue.toString() : "1"); // Ensure it's not less than 1
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    }
  };
  const getProd = (idP) => {
    console.log(idP);
    get_product({
      id: idP,
    })
      .then((result) => {
        //  console.log("result" + result);
        if (result.data.product_type === "variation") {
          get_product({
            id: result.data.parent_id,
          })
            .then((result1) => {
              //  console.log("result" + result);

              if (result1.error) {
                setError(result1.error);
              } else {
                // setcart(result.data);
                navigation.navigate("Product", { product: result1.data });
                console.log(result1.data);
              }
            })
            .catch((error) => {
              setError(error.message);
            })
            .finally(() => {
              // set
            });
        } else {
          if (result.error) {
            setError(result.error);
          } else {
            // setcart(result.data);
            navigation.navigate("Product", { product: result.data });
            console.log(result.data);
          }
        }
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };
  return (
    <View style={styles.container}>
      {cart ? (
        <>
          <View style={styles.heart}>
            <Checkbox
              value={cart?.selected}
              onValueChange={() => shopProdLike(shopIndex, index)}
            />
          </View>

          <TouchableOpacity
            onPress={() => getProd(cart.items[0].product.product_id)}
            style={styles.imgWrap}
          >
            <Image
              style={{ width: 50, height: 50, resizeMode: "cover" }}
              source={{ uri: `${cart.items[0].product?.product_image}` }}
            />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => getProd(cart.items[0].product?.product_id)}
            style={styles.wrapper}
          >
            <View style={styles.details}>
              <Text style={styles.text} numberOfLines={2}>
                {cart.items[0]?.product?.name}
              </Text>

              <View style={styles.rateCon}>
                {cart.items[0].price ? (
                  <>
                    <View style={styles.priceCon}>
                      <Text
                        style={
                          cart.sale_price
                            ? styles.textPricePromo
                            : styles.textPrice
                        }
                      >
                        ₱
                        {parseFloat(cart.items[0].price).toLocaleString(
                          "en-US"
                        )}
                      </Text>
                      {cart.sale_price ? (
                        <Text style={styles.textPrice}>
                          {/* {" "}
                      {(cart.regular_price * (1 - cart.sale_price / 100)).toFixed(2) }{" "}

                      <Text style={{ fontWeight: "400" }}>
                        (-{cart.sale_price}%)
                      </Text> */}
                          {cart.sale_price}
                        </Text>
                      ) : null}
                    </View>
                  </>
                ) : (
                  <Text>No price </Text>
                )}
              </View>
            </View>
          </TouchableOpacity>
          <View style={styles.quantity}>
            <TouchableOpacity
              style={styles.buttonQty}
              onPress={() => handleInputChange("add")}
            >
              <FontAwesomeIcon icon={faPlus} color={"#888888"} size={10} />
            </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("minus")}
            >
              <FontAwesomeIcon icon={faMinus} color={"#888888"} size={10} />
            </TouchableOpacity>
          </View>
        </>
      ) : null}
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    // width: "95%",
    margin: 5,
    borderRadius: 6,
    borderColor: "#dddd",
    borderWidth: 1,
    overflow: "hidden",
    flexDirection: "row",
    padding: 10,
    backgroundColor: "#ffffff",
    alignItems: "center",
  },

  header: {
    position: "fixed",
    width: "100%",
    top: 0,
  },
  footer: {
    // position: "absolute",
    bottom: 0,
    width: "100%",
  },
  imgWrap: {
    padding: 10,
  },
  wrapper: {
    height: "85%",
    width: "60%",
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 10,
  },
  textPrice: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  details: {
    // width: "50%",
  },
  text: {
    fontSize: 13,
  },
  quantity: {
    // flexDirection:'row',
    justifyContent: "space-between",
    alignItems: "center",
  },
  buttonQty: {
    backgroundColor: "#eee",
    padding: 5,
    margin: 5,
  },
});

export default CartSubCard;
