import {
  faArrowLeft,
  faCartShopping,
  faComment,
  faHeart,
  faMessage,
  faStar,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import {
  useIsFocused,
  useNavigation,
  useRoute,
} from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  Dimensions,
  FlatList,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import Modal from "react-native-modal";

import RenderHTML from "react-native-render-html";
import BottomNav from "../../components/product/BottomNav";
import ShopPrev from "../../components/product/ShopPrev";
import Variation from "../../components/product/Variation";
import {
  get_customer,
  update_customer,
} from "../../services/api/controllers/customers";
import { useToast } from "react-native-toast-notifications";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { get_orders_by_customer } from "../../services/api/controllers/order";
import CheckOutModal from "../../components/product/CheckOutModal";
import CustomerReview from "../../components/product/CustomerReview";
import Swiper from "react-native-swiper";

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

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

const ProductSinglePage = ({ setcartList, cartList, prod }) => {
  const route = useRoute();
  const { product } = route.params;
  const [activeImg, setactiveImg] = useState(0);
  const [imagesArray, setimagesArray] = useState([]);

  const toast = useToast();
  const [user, setuser] = useState([]);
  const [error, seterror] = useState([]);
  const [liked, setliked] = useState([]);
  const [isLiked, setisLiked] = useState(false);
  const [cartCount, setcartCount] = useState();
  const [modalVisible, setModalVisible] = useState(false);
  const [variations, setvariations] = useState([]);
  const [activeVar, setactiveVar] = useState(null);
  const [activeProduct, setactiveProduct] = useState(product ?? []);
  const [isLoggedin, setisLoggedin] = useState(false);
  const [variablePrice, setvariablePrice] = useState("");

  const isFocused = useIsFocused();
  useEffect(() => {
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          setisLoggedin(true);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, [isFocused]);
  useEffect(() => {
    setactiveProduct(product);
    const purch = prod?.filter((item) => item?.parent_id === product._id);

    const newPurch = [product, ...purch];
    setvariations(newPurch);

    function getLowestHighestPrice(variation) {
      let lowestPrice = Infinity;
      let highestPrice = -Infinity;
      let hasPrice = false;

      variation.forEach((item) => {
        let price = null;

        // If sale_price is available and not an empty string, use it; otherwise, use regular_price
        if (item.sale_price && item.sale_price !== "") {
          price = parseFloat(item.sale_price);
        } else if (item.regular_price && item.regular_price !== "") {
          price = parseFloat(item.regular_price);
        }

        // Update lowest and highest prices
        if (price !== null) {
          hasPrice = true;
          lowestPrice = Math.min(lowestPrice, price);
          highestPrice = Math.max(highestPrice, price);
        }
      });

      if (!hasPrice) {
        return null;
      }

      // If lowest and highest prices are the same, return that price alone
      if (lowestPrice === highestPrice) {
        return `${lowestPrice}`;
      }

      // Return the range of lowest to highest prices
      return `${lowestPrice}-${highestPrice}`;
    }
    const priceRange = getLowestHighestPrice(purch);
    setvariablePrice(priceRange);
    console.log("-----------------------Price Range:", priceRange);
  }, [isFocused]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    if (liked) {
      // console.log(liked?.products);

      const exists = liked?.products?.some(
        (prod) => prod._id === activeProduct?._id
      );
      // console.log("exist" + exists);
      // console.log("product" + product?._id);

      if (
        // exists !== [] &&
        // exists &&
        // exists !== "" &&
        // exists !== undefined &&
        // exists !== exists?.length < 0 &&
        // exists !== " "
        exists
      ) {
        // console.log("exx");
        setisLiked(true);
      }
    }
  }, [liked]);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    // if (liked) {
    // console.log(liked?.products);

    const exists = liked?.products?.some(
      (prod) => prod._id === activeProduct?._id
    );
    // console.log("exist" + exists);
    // console.log("product" + product?._id);

    if (
      // exists !== [] &&
      // exists &&
      // exists !== "" &&
      // exists !== undefined &&
      // exists !== exists?.length < 0 &&
      // exists !== " "
      exists
    ) {
      // console.log("exx");
      setisLiked(true);
    } else {
      setisLiked(false);
    }
    // }
  }, [activeProduct]);
  useEffect(() => {
    const actProd = [...variations];
    setisLiked(false);
    setactiveProduct(actProd[activeVar]);
  }, [activeVar]);

  useEffect(() => {
    // setrefresh(isrefresh);
    setactiveProduct(product);
    AsyncStorage.getItem("userData")
      .then((pass) => {
        // console.log("mm "+pass._id);
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        get_customer({ id: userDataArray[0]?._id })
          .then((result) => {
            // console.log(result.data);

            if (result.error) {
              seterror(result.error);
            } else {
              // const exists = result?.data?.favorites?.some((prod) => prod._id === product?._id);
              // console.log( exists)
              // if (exists) {
              // console.log( "heyyyy")

              //   setisLiked(true);
              // }
              setliked(result?.data?.favorites);
            }
          })
          .catch((error) => {
            // setError(error.message);
            console.log(error.message);
          })
          .finally(() => {
            // setprodIsLoading(false); // Set loading to false when done loading
          });
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    // console.log("get cutomer add :" + user[0]?.login_id);
    const purch = prod?.filter((item) => item?.parent_id === product._id);

    const newPurch = [product, ...purch];
    setvariations(newPurch);
    // console.log("var--------- " + purch);
  }, []);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    AsyncStorage.getItem("userData")
      .then((pass) => {
        if (pass !== null) {
          const userDataArray = JSON.parse(pass);
          setuser(userDataArray);
          console.log(userDataArray[0]?._id);
          get_orders_by_customer({
            id: userDataArray[0]?._id,
          })
            .then((result) => {
              if (result.error) {
                // setError(result.error);
              } else {
                const purch = result.data?.filter(
                  (item) => item.status === "Cart" || item.status === "CART"
                );
                setcartCount(purch);
                // console.log("purchhh" + purch);
              }
            })
            .catch((error) => {
              // setError(error.message);
              setcartCount([]);
            })
            .finally(() => {
              // setprodIsLoading(false); // Set loading to false when done loading
            });
          console.log(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  console.log("act " + activeImg);
  const navigation = useNavigation();
  // Botto

  const source = {
    html: `
  ${activeProduct?.specifications}`,
  };

  // const imagesArray = activeProduct?.images
  //   ? activeProduct?.images?.split(",")
  //   : activeProduct?.product_image
  //       ?.split(",")
  //       .map((imageUrl) => ({ image: imageUrl.trim() }));
  // console.log(imagesArray);
  // console.log(
  //   "============================imagesArray==========================="
  // );

  useEffect(() => {
    const imagesArray1 = activeProduct?.images
      ? activeProduct?.images?.split(",")
      : activeProduct?.product_image
          ?.split(",")
          .map((imageUrl) => ( imageUrl.trim() ));
    setimagesArray(imagesArray1 ?? "");
    console.log(
      "============================imagesArray==========================="
    );
    console.log(imagesArray1);
    console.log(
      "============================imagesArray==========================="
    );
    // setactiveImg(0);
  }, [activeProduct]);

  // const likeProduct = (id) => {};
  const images = [{ image: "" }];
  const likeClicked = () => {
    if (!isLiked) {
      // if (liked?.length > 0 && liked !== undefined && liked !== []) {
      const like = liked;
      like?.products?.push(activeProduct);
      update_customer({
        id: user[0]._id,
        body: {
          favorites: like,
        },
      })
        .then((result) => {
          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
            // console.log(result.data);
            setisLiked(true);

            // setaddreses(result.data.address);
            // toast.show("Successfully changed the Billing Address!", {
            //   type: "success",
            //   placement: "top",
            //   duration: 2000,
            //   offset: 30,
            //   animationType: "slide-in",
            // });
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
    } else {
      // const updatedFavorites = liked.map((favorite) => {
      const updatedProduct = liked.products.filter(
        (prod) => prod._id !== activeProduct?._id
      );
      //   return { ...favorite, products: updatedProduct };
      // });
      const fave = {
        products: updatedProduct,
        vendors: liked.vendors,
      };
      update_customer({
        id: user[0]._id,
        body: {
          favorites: fave,
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
            setisLiked(false);

            // setaddreses(result.data.address);
            // toast.show("Successfully changed the Billing Address!", {
            //   type: "success",
            //   placement: "top",
            //   duration: 2000,
            //   offset: 30,
            //   animationType: "slide-in",
            // });
          }
        })
        .catch((error) => {
          // setError(error.message);
          console.log(error.message);
        })
        .finally(() => {
          // setprodIsLoading(false); // Set loading to false when done loading
        });
    }
  };
  const handleIndexChanged = (index) => {
    // This function will be called whenever the active slide changes
    setactiveImg(parseInt(index) - 1);
  };
  return (
    <View style={styles.container}>
      <ScrollView>
        <View style={styles.headerCon}>
          <TouchableOpacity
            onPress={() => navigation.goBack()}
            style={styles.backIcon}
          >
            <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => navigation.navigate("Cart")}
            style={styles.backIcon}
          >
            {/* <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} /> */}
            <FontAwesomeIcon
              icon={faCartShopping}
              color={"#FFAA00"}
              size={25}
            />
            <Text style={styles.cartIconBadge}>
              {cartCount?.length > 99 ? "99+" : cartCount?.length ?? 0}
            </Text>
          </TouchableOpacity>
        </View>
        <View tyle={styles.wrapper}>
          <View tyle={styles.wrapperSwiper}>
            <Swiper
              style={styles.wrapperSwiper1}
              // autoplay
              loop={false}
              index={activeImg} // Set the initial active slide index
              showsPagination={false}
              onIndexChanged={(index) => {
                setactiveImg(index), console.log(index + " change");
              }} // Callback when the active slide changes
            >
              {imagesArray?.map((e, index) => (
                <Image
                  key={index}
                  style={{
                    width: width,
                    height: 450,
                    resizeMode: "contain",
                  }}
                  source={{
                    uri: `${
                      e !== ""
                        ? e
                        : "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg"
                    }`,
                  }}
                />
              ))}
            </Swiper>
          </View>

          <View style={styles.imgPrevCon}>
            <FlatList
              // inverted
              //   style={styles.wrapper}
              horizontal
              data={imagesArray ? imagesArray : images}
              showsHorizontalScrollIndicator={false}
              renderItem={({ item, index }) => {
                return (
                  <TouchableOpacity
                    onPress={() => {
                      setactiveImg(Math.abs(index));
                    }}
                  >
                    <View
                      style={
                        activeImg === Math.abs(index)
                          ? styles.imgPrevCardActive
                          : styles.imgPrevCard
                      }
                    >
                      <Image
                        style={styles.imgPrev}
                        source={{
                          uri:
                            item !== ""
                              ? item
                              : "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg",
                        }}
                      />
                      <Text
                        style={{
                          color: "#000",
                          fontSize: 10,
                          flexWrap: "wrap",
                        }}
                      ></Text>
                    </View>
                  </TouchableOpacity>
                );
              }}
            />
          </View>
          <View
            style={{
              width: "100%",
              padding: 10,
              backgroundColor: "#fff",
              border: "none",
              borderColor: "#f3f3f3",
              borderWidth: 1,
            }}
          >
            <Text style={styles.text}>{activeProduct.product_name}</Text>
            {product.product_type === "variable" ? (
              <>
                {activeVar !== null ? (
                  <View style={styles.priceCon}>
                    <Text
                      style={
                        activeProduct.sale_price
                          ? styles.textPricePromo
                          : styles.textPrice
                      }
                    >
                      {activeProduct?.regular_price &&
                      activeProduct?.regular_price !== null ? (
                        "₱" + activeProduct?.regular_price
                      ) : (
                        <TouchableOpacity style={styles.inquire}>
                          <Text style={styles.inquire}>Inquire for price</Text>
                        </TouchableOpacity>
                      )}
                    </Text>
                    {activeProduct.sale_price ? (
                      <Text style={styles.textPrice}>
                        {/* {" "}
                  {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "}
                  <Text style={{ fontWeight: "400" }}>(-{product.sale_price}%)</Text> */}{" "}
                        {activeProduct?.sale_price}
                      </Text>
                    ) : null}
                  </View>
                ) : (
                  <View style={styles.priceCon}>
                    <Text style={styles.textPrice}>
                      {" "}
                      {variablePrice ? (
                        " ₱" + variablePrice
                      ) : (
                        <TouchableOpacity>
                          <Text style={styles.inquire}>
                            Contact Seller for the price
                          </Text>
                        </TouchableOpacity>
                      )}
                    </Text>
                    {/* {activeProduct.sale_price ? (
                      <Text style={styles.textPrice}>
                        {/* {" "}
                  {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "}
                  <Text style={{ fontWeight: "400" }}>(-{product.sale_price}%)</Text> */}
                    {/* {activeProduct?.sale_price}
                      </Text> */}
                    {/* ) : null}  */}
                  </View>
                )}
              </>
            ) : (
              <View style={styles.priceCon}>
                <Text
                  style={
                    activeProduct.sale_price
                      ? styles.textPricePromo
                      : styles.textPrice
                  }
                >
                  {activeProduct?.regular_price &&
                  activeProduct?.regular_price !== null ? (
                    "₱" + activeProduct?.regular_price
                  ) : (
                    <TouchableOpacity style={styles.inquire}>
                      <Text style={styles.inquire}>Inquire for price</Text>
                    </TouchableOpacity>
                  )}
                </Text>
                {activeProduct.sale_price ? (
                  <Text style={styles.textPrice}>
                    {/* {" "}
                    {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "}
                    <Text style={{ fontWeight: "400" }}>(-{product.sale_price}%)</Text> */}{" "}
                    {activeProduct?.sale_price}
                  </Text>
                ) : null}
              </View>
            )}

            <View style={styles.footer}>
              {product?.rate ? (
                <View style={styles.rateCon}>
                  <FontAwesomeIcon icon={faStar} color={"#eede00"} size={15} />
                  <Text style={styles.textRate}>
                    {product?.rate ?? 0} ({product?.raterTotal ?? 0})
                  </Text>
                </View>
              ) : (
                <View style={styles.rateCon}>
                  <FontAwesomeIcon icon={faStar} color={"#eede00"} size={20} />
                  <Text style={styles.textRate}> 0</Text>
                </View>
              )}
              <View style={styles.rateCon}>
                <TouchableOpacity
                  style={styles.messageBtn1}
                  onPress={() => {
                    isLoggedin
                      ? likeClicked(activeProduct?._id)
                      : navigation.navigate("Login");
                  }}
                >
                  <FontAwesomeIcon
                    icon={faHeart}
                    color={isLiked ? "#ff5c5c" : "#dbdbdb"}
                    size={35}
                  />
                </TouchableOpacity>
                {/* <Text style={styles.textRate}> 0</Text> */}
                <TouchableOpacity
                  onPress={() => navigation.navigate("Chat")}
                  style={styles.messageBtn}
                >
                  <FontAwesomeIcon
                    icon={faComment}
                    size={25}
                    color={"#698600"}
                  />
                  {/* <Text style={styles.btnText}>Chat</Text> */}
                </TouchableOpacity>
              </View>
            </View>
            <View style={styles.footer}>
              <Text style={styles.textMin}>
                {activeProduct?.minimum_order ? (
                  <>
                    {" "}
                    min. order:{" "}
                    {activeProduct?.minimum_order !== "" ||
                    activeProduct?.minimum_order !== null
                      ? activeProduct?.minimum_order
                      : 1}{" "}
                    {activeProduct?.per ?? ""}
                  </>
                ) : null}
              </Text>
              <Text style={styles.textSold}>
                stock: {activeProduct?.stock ?? 0}
              </Text>
              <Text style={styles.textSold}>
                {activeProduct?.sold ?? 0} sold
              </Text>
            </View>
          </View>
        </View>
        {product.product_type === "variable" ? (
          <Variation
            prod={product}
            vars={variations}
            setactiveVar={setactiveVar}
          />
        ) : null}

        <ShopPrev shopId={product?.vendor_api_id} />
        <Text style={styles.header1}>Description</Text>
        <View style={{ padding: 15 }}>
          {activeProduct?.specifications ? (
            <RenderHTML contentWidth={width} source={source} />
          ) : (
            <>
              <Text>{product.product_name}</Text>
            </>
          )}
        </View>
        {/* <CustomerReview /> */}
      </ScrollView>
      <View style={styles.footerButton}>
        <BottomNav
          product={activeProduct ? activeProduct : null}
          cartList={cartList}
          setcartList={setcartList}
          setModalVisible={setModalVisible}
          activeVar={activeVar}
        />
      </View>
      <Modal
        animationType="slide"
        animationIn={"bounceInUp"}
        transparent={true}
        isVisible={modalVisible}
        onSwipeComplete={() => setModalVisible(false)}
        swipeDirection={"down"}
        // swipeThreshold="100"
        backdropOpacity={0.1}
        style={{ margin: 0 }}
        propagateSwipe={true}
        deviceWidth={deviceWidth}
        // deviceHeight={deviceHeight}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        {/* <ReceiptCard onRequestClose={setModalVisible} cart={cart} /> */}
        <CheckOutModal setModalVisible={setModalVisible} />
      </Modal>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    height: "100%",
    width: "100%",
  },
  headerCon: {
    // position: "absolute",
    // height: 90,
    width: "100%",
    display: "flex",
    justifyContent: "space-between",
    flexDirection: "row",
    top: 0,
    padding: 15,
    // backgroundColor: "#f75656",
  },
  header1: {
    // position: "fixed",
    width: "100%",
    top: 0,
    fontWeight: "bold",
    paddingHorizontal: 15,
  },
  backIcon: {
    // marginLeft: 20,
    backgroundColor: "#f1f1f1",
    // backgroundColor: "#98eb00",

    justifyContent: "center",
    alignItems: "center",
    width: 50,
    height: 50,
    borderRadius: 50,
    marginBottom: 10,
  },
  cartIconBadge: {
    position: "absolute",
    top: 0,
    right: 0,
    borderRadius: 50,
    backgroundColor: "#f75656",
    width: 18,
    height: 18,
    textAlign: "center",
    justifyContent: "center",
    alignItems: "center",
    color: "#fff",
    fontSize: 11,
    // padding: 10,
  },
  inquire: {
    fontSize: 16,
    fontWeight: "600",
    // textTransform: "capitalize",
    // textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  wrapper: {
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  wrapperSwiper: {
    // width: width,
    height: "100%",
    // flex: 1,
    // height: 450,
    // zIndex: 1000,
  },
  wrapperSwiper1: {
    // width: "100%",
    // width: width,
    height: 450,
    // maxHeight: "60%",
    // backgroundColor: "#f75656",

    // height: 500,
    // zIndex: 1000,
  },
  header: {
    fontSize: 14,
    fontWeight: "700",
    textTransform: "uppercase",
  },
  text: {
    fontSize: 16,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#333",
    letterSpacing: 0.5,
  },
  imgPrevCon: {
    borderWidth: 1,
    borderColor: "#eeee",
  },
  imgPrevCard: {
    borderWidth: 1,
    borderColor: "#eeee",
    width: 110,
    height: 110,
    justifyContent: "center",
    alignItems: "center",
    padding: 2,
  },
  imgPrevCardActive: {
    borderWidth: 5,
    borderColor: "#585858ed",
    width: 110,
    height: 110,
    justifyContent: "center",
    alignItems: "center",
    padding: 2,
  },
  imgPrev: {
    width: 100,
    height: 100,
    resizeMode: "cover",
    // margin: "auto",
    // borderRadius: 10,
    top: 7,
    // padding: 10,
  },
  messageBtn: {
    // width: 80,
    // height: 80,
    marginLeft: 20,
    flexDirection: "row",
    resizeMode: "cover",
    borderRadius: 10,
    backgroundColor: "#dfff6c",
    padding: 6,
  },
  btnText: {
    fontSize: 14,
    fontWeight: "600",
    // textTransform: "uppercase",
    paddingHorizontal: 5,
    color: "#698600",
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 10,
  },
  textPrice: {
    fontSize: 21,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 21,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  textMin: {
    fontSize: 13,
    fontWeight: "600",
    color: "#bdbdbd",
  },
  textSold: {
    fontSize: 13,
    fontWeight: "600",
    color: "#bdbdbd",
  },
  rateCon: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
  },
  textRate: {
    fontSize: 13,
    color: "#838383",
  },
  img: {
    width: 400,
    height: 200,
    resizeMode: "cover",
    margin: "auto",
    borderRadius: 10,
  },

  footer: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  footerButton: {
    bottom: 0,
    width: "100%",
  },
});

export default ProductSinglePage;
