import { faStar } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useIsFocused, useNavigation } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Button,
  Dimensions,
  Image,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import FastImage from "react-native-fast-image";
import nobg from "../../../../assets/bg-no-img-big.jpg";
const width = Dimensions.get("window").width;
// import { LazyLoadImage } from 'react-native-lazyload';
const ProductCard = ({ product, productList }) => {
  const navigation = useNavigation();
  const [variablePrice, setvariablePrice] = useState("");
  const isFocused = useIsFocused();

  const [imageLoaded, setImageLoaded] = useState(false);
  const url = product?.product_image;
  // const path = url.replace("https://obanana.com", "http://old.obanana.shop");
  // console.log("old.obanana.shop"+path)

  useEffect(() => {
    // setactiveProduct(product);
    const purch = productList?.filter(
      (item) => item?.parent_id === product._id
    );
    // setvariations(purch);

    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]);
  return (
    <TouchableOpacity
      activeOpacity={0.7}
      style={styles.container}
      onPress={() => navigation.navigate("Product", { product })}
    >
      {/* {imageLoaded ? ( */}
      <Image
        style={{ width: "100%", height: width * 0.45, resizeMode: "cover" }}
        source={{
          uri:
            product?.product_image !== ""
              ? //  path
                product?.product_image
              : "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg",
        }}
      />
      {/* ) : (
          <ActivityIndicator size="large" color="#000" />
        )} */}
      <View style={{ padding: 10, backgroundColor: "#fff" }}>
        <Text style={styles.text} numberOfLines={2}>
          {product.product_name}
        </Text>
        {product.product_type === "variable" ? (
          <View style={styles.priceCon}>
            <Text
              style={
                product.sale_price ? styles.textPricePromo : styles.textPrice
              }
            >
              {variablePrice ? (
                " ₱" + variablePrice
              ) : (
                <TouchableOpacity>
                  <Text style={styles.inquire}>Inquire for price</Text>
                </TouchableOpacity>
              )}
            </Text>
          </View>
        ) : (
          <View style={styles.priceCon}>
            <Text
              style={
                product.sale_price ? styles.textPricePromo : styles.textPrice
              }
            >
              {product?.regular_price && product?.regular_price !== null ? (
                "₱" + parseFloat(product?.regular_price).toLocaleString("en-US")
              ) : (
                <TouchableOpacity style={styles.inquire}>
                  <Text style={styles.inquire}>Inquire for price</Text>
                </TouchableOpacity>
              )}
            </Text>
            {product.sale_price ? (
              <Text style={styles.textPrice}>
                {" "}
                {/* {(product.regular_price * (1 - product.promo / 100)).toFixed(2) }{" "} */}
                {parseFloat(product?.sale_price).toLocaleString("en-US")}
                {/* <Text style={{ fontWeight: "400" }}>(-{product.promo}%)</Text> */}
              </Text>
            ) : null}
          </View>
        )}
        <View style={styles.footer}>
          {/* <Text style={styles.textMin}>
            min. order: {product.min} {product.per}
          </Text> */}
          <Text style={styles.textMin}>stock: {product.stock}</Text>
          <Text style={styles.textSold}>{product.sold} sold</Text>
        </View>
        {product.rate ? (
          <View style={styles.rateCon}>
            <FontAwesomeIcon icon={faStar} color={"#eede00"} size={15} />
            <Text style={styles.textRate}>
              {product.rate} ({product.raterTotal})
            </Text>
          </View>
        ) : null}
      </View>
    </TouchableOpacity>
  );
};
const styles = StyleSheet.create({
  container: {
    // flex: 1,
    // backgroundColor: "#ff3333",
    width: "95%",
    margin: 5,
    borderRadius: 6,
    borderColor: "#dddd",
    overflow: "hidden",
  },
  wrapper: {
    width: "100%",
    //   height: 200,
    alignItems: "center",
    justifyContent: "center",
    // backgroundColor: "#ffaa00",
  },
  header: {
    fontSize: 14,
    fontWeight: "700",
    textTransform: "uppercase",
  },
  text: {
    fontSize: 13,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#333",
    letterSpacing: 0.5,
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 4,
  },
  textPrice: {
    fontSize: 16,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 16,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  inquire: {
    fontSize: 16,
    fontWeight: "600",
    // textTransform: "capitalize",
    // textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  textMin: {
    fontSize: 11,
    fontWeight: "600",
    // textTransform: "capitalize",
    color: "#bdbdbd",
  },
  textSold: {
    fontSize: 11,
    fontWeight: "600",
    // textTransform: "capitalize",
    color: "#bdbdbd",
  },
  rateCon: {
    flexDirection: "row",
    // justifyContent:'center',
    alignItems: "center",
    paddingVertical: 3,
  },
  textRate: {
    fontSize: 12,
    color: "#838383",
  },
  img: {
    width: 400,
    height: 200,
    resizeMode: "cover",
    margin: "auto",
    borderRadius: 10,
    // backgroundColor: "#ffaa00",
  },
  footer: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
});
export default ProductCard;
