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 ( navigation.goBack()} style={styles.backIcon} > navigation.navigate("Cart")} style={styles.backIcon} > {/* */} {cartCount?.length > 99 ? "99+" : cartCount?.length ?? 0} { setactiveImg(index), console.log(index + " change"); }} // Callback when the active slide changes > {imagesArray?.map((e, index) => ( ))} { return ( { setactiveImg(Math.abs(index)); }} > ); }} /> {activeProduct.product_name} {product.product_type === "variable" ? ( <> {activeVar !== null ? ( {activeProduct?.regular_price && activeProduct?.regular_price !== null ? ( "₱" + activeProduct?.regular_price ) : ( Inquire for price )} {activeProduct.sale_price ? ( {/* {" "} {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "} (-{product.sale_price}%) */}{" "} {activeProduct?.sale_price} ) : null} ) : ( {" "} {variablePrice ? ( " ₱" + variablePrice ) : ( Contact Seller for the price )} {/* {activeProduct.sale_price ? ( {/* {" "} {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "} (-{product.sale_price}%) */} {/* {activeProduct?.sale_price} */} {/* ) : null} */} )} ) : ( {activeProduct?.regular_price && activeProduct?.regular_price !== null ? ( "₱" + activeProduct?.regular_price ) : ( Inquire for price )} {activeProduct.sale_price ? ( {/* {" "} {(activeProduct.regular_price * (1 - activeProduct.sale_price / 100)).toFixed(2)}{" "} (-{product.sale_price}%) */}{" "} {activeProduct?.sale_price} ) : null} )} {product?.rate ? ( {product?.rate ?? 0} ({product?.raterTotal ?? 0}) ) : ( 0 )} { isLoggedin ? likeClicked(activeProduct?._id) : navigation.navigate("Login"); }} > {/* 0 */} navigation.navigate("Chat")} style={styles.messageBtn} > {/* Chat */} {activeProduct?.minimum_order ? ( <> {" "} min. order:{" "} {activeProduct?.minimum_order !== "" || activeProduct?.minimum_order !== null ? activeProduct?.minimum_order : 1}{" "} {activeProduct?.per ?? ""} ) : null} stock: {activeProduct?.stock ?? 0} {activeProduct?.sold ?? 0} sold {product.product_type === "variable" ? ( ) : null} Description {activeProduct?.specifications ? ( ) : ( <> {product.product_name} )} {/* */} setModalVisible(false)} swipeDirection={"down"} // swipeThreshold="100" backdropOpacity={0.1} style={{ margin: 0 }} propagateSwipe={true} deviceWidth={deviceWidth} // deviceHeight={deviceHeight} onRequestClose={() => { setModalVisible(!modalVisible); }} > {/* */} ); }; 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;