import { faHeart } from "@fortawesome/free-solid-svg-icons";
import { faArrowLeft, faStar } 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 React, { useEffect, useRef, useState } from "react";
import {
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import Tab from "../../components/shop/Tab";
import {
  get_customer,
  update_customer,
} from "../../services/api/controllers/customers";
import { get_products_by_vendor } from "../../services/api/controllers/product";
import { get_vendor } from "../../services/api/controllers/vendor";

const ShopSinglePage = ({ route,productList }) => {
  const navigation = useNavigation();
  const { product } = route.params;
  const [prod, setprod] = useState([]);
  const [products, setproducts] = useState([]);

  const scrollViewRef = useRef(null);
  const [isEndReached, setEndReached] = useState(false);

  const [user, setuser] = useState([]);
  const [error, seterror] = useState([]);
  const [item, setitem] = useState(20);
  const [liked, setliked] = useState([]);
  const [isLiked, setisLiked] = useState(false);
  console.log(product);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    if (liked) {
      console.log(liked?.vendors);

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

      if (
        exists !== [] &&
        exists &&
        exists !== "" &&
        exists !== undefined &&
        exists !== exists?.length < 0 &&
        exists !== " "
      ) {
        console.log("exx");
        setisLiked(true);
      }
    }
  }, [liked]);

  useEffect(() => {
    // setrefresh(isrefresh);
    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 {
              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);
  }, []);

  useEffect(() => {
    get_products_by_vendor({
      id: product._id,
    })
      .then((result) => {
        if (result.status === 200) {
          console.log("successful get vendor products: " + result.data);
          // setvendorName(result.data.user_login);
          setproducts(result.data.filter(
            (item) => item.product_type !== "variation"  &&
            item.product_image !== "" &&
            item.product_image !== null
          ));
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);
  useEffect(() => {
    setprod(products.splice(0, item ?? 0));
  }, [products]);

  useEffect(() => {
    // if (isEndReach===true) {
    // console.log("onEndReached event triggered");
    // console.log("item:", item);
    // console.log("product length:", product.length);
    if (item <= products.length) {
      // setprod(product.splice(1, item));

      setprod([...prod, ...products.slice(item, item + 10)]);
      // setitem(item + 10);
    }
    // }
  }, [item]);
  const handleScroll = (event) => {
    const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
    const isAtEnd =
      layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;

    if (isAtEnd) {
      // You've reached the end of the ScrollView
      setEndReached(true);
      console.log("end here");
      setitem(item + 15);
      // setEndReached(false);
      // console.log("item" + item);
    }
  };
  const likeClicked = () => {
    if (!isLiked) {
      // if (liked?.length > 0 && liked !== undefined && liked !== []) {
      const like = liked;
      like?.vendors?.push(product);
      update_customer({
        id: user[0]._id,
        body: {
          favorites: like,
        },
      })
        .then((result) => {
          console.log(result.data);

          if (result.error) {
            seterror(result.error);
          } else {
            setliked(result?.data?.favorites);
            setisLiked(true);
          }
        })
        .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.vendors.filter(
        (prod) => prod._id !== product?._id
      );
      //   return { ...favorite, vendors: updatedProduct };
      // });
      const fave = {
        products:liked?.products ,
        vendors: updatedProduct,
      };
      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
        });
    }
  };
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => navigation.goBack()}
          style={styles.backIcon}
        >
          <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
        </TouchableOpacity>
      </View>
      <ScrollView
        style={styles.wrapper}
        ref={scrollViewRef}
        onScroll={handleScroll}
      >
        <View style={styles.top}>
          <View style={styles.topWrap}>
            <View style={styles.topBanner}>
              <Image
                style={styles.imgs}
                source={{
                  uri: product?.vendor_banner ?? product?.vendor_image ?? "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg",
                }}
              />
            </View>
            <View style={styles.topDetails}>
              <View style={styles.topDetailsMain}>
                <View style={styles.topDetailsMainProfile}>
                  <Image
                    style={styles.topDetailsMainProfileImg}
                    source={{
                      uri: product?.vendor_image ?? "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg",
                    }}
                  />
                </View>
                <View style={styles.topDetailsMainProfileDetails}>
                  <View style={styles.topDetailsMainProfileDetailsContents}>
                    <Text style={styles.text} numberOfLines={1}>
                      {product.user_login}
                    </Text>
                    <View style={styles.rateCon}>
                      <>
                        <Text style={styles.textHead}>Address: </Text>

                        <Text style={styles.textRate}>
                          {product?.address[0]?.city}, {product?.address[0]?.province}{" "}
                        </Text>
                      </>
                    </View>
                    <View style={styles.rateCon}>
                      {/* {product.rate ? ( */}
                      <>
                        <Text style={styles.textHead}>Rating: </Text>
                        <FontAwesomeIcon
                          icon={faStar}
                          color={"#eede00"}
                          size={15}
                        />
                        <Text style={styles.textRate}>
                          {product.rate??0} ({product.raterTotal??0})
                        </Text>
                      </>
                      {/* ) : (
                          <Text>No rating </Text>
                        )} */}
                    </View>
                    <View style={styles.rateCon}>
                      {/* {product.respoTime ? ( */}
                      <>
                        <Text style={styles.textHead}>
                          Average Response Time:{" "}
                        </Text>

                        <Text style={styles.textRate}>
                          {product.respoTime??0} 
                        </Text>
                      </>
                      {/* ) : (
                          <Text>No rating </Text>
                        )} */}
                    </View>
                  </View>
                </View>
                <TouchableOpacity
                  style={styles.topDetailsMainProfileDetailsFollow}
                  onPress={() => {
                    likeClicked();
                  }}
                >
                  {isLiked ? (
                    <FontAwesomeIcon
                      icon={faHeart}
                      color={"#d40000"}
                      size={20}
                    />
                  ) : (
                    <FontAwesomeIcon
                      icon={faHeart}
                      color={"#c0c0c0"}
                      size={20}
                    />
                  )}

                  {/* <Text style={styles.textFollow} numberOfLines={1}>
                    Follow
                  </Text> */}
                </TouchableOpacity>
              </View>
              <View style={styles.bottomDetails}>
                {/* <Text style={styles.textHead2}>Address: </Text> */}

                <View style={styles.bottomDetailsCat}></View>
              </View>
            </View>
          </View>
        </View>
        <View style={styles.bottom}>
          <Tab info={product.info} prod={prod} item={item} productList={productList}/>
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffffff",
    width: "100%",
    height: "100%",
    flex: 1,
  },
  wrapper: {
    width: "100%",
    height: "100%",
  },
  header: {
    // position: "fixed",
    width: "100%",
    top: 0,
    paddingVertical: 10,
    marginBottom: 5,
    marginLeft: 15,
    zIndex: 10,
    // backgroundColor: "#ff0909",
  },
  backIcon: {
    // width:10
  },
  imgs: {
    width: "100%",
    height: 220,
    resizeMode: "cover",
    margin: "auto",
    // borderRadius: 10,
  },
  tabs: {
    height: 80,
    width: "100%",
    position: "absolute",
    bottom: 100,
  },
  top: {
    width: "100%",
    // top:-20,
    alignItems: "center",
    justifyContent: "center",
  },
  topWrap: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  topBanner: {
    width: "100%",
  },
  topDetails: {
    width: "100%",
  },
  topDetailsMain: {
    width: "100%",
    flexDirection: "row",
    justifyContent: "space-between",
    paddingHorizontal: 10,
    // backgroundColor: "#ff3131",
    paddingTop: 10,
  },
  topDetailsMainProfile: {
    width: 110,
    height: 110,
    borderRadius: 200,
    top: -30,
    borderColor: "#dddd",
    borderWidth: 1,
    backgroundColor: "#fff",
    justifyContent: "center",
    alignItems: "center",
  },
  topDetailsMainProfileImg: {
    width: 97,
    height: 97,
    borderRadius: 200,
    borderColor: "#dddd",
    borderWidth: 1,
  },
  topDetailsMainProfileDetails: {
    width: "55%",
  },
  topDetailsMainProfileDetailsContents: {
    margin: 0,
  },

  topDetailsMainProfileDetailsFollow: {
    borderColor: "#dddd",
    borderWidth: 1,
    padding: 0,
    paddingHorizontal: 15,
    flexDirection: "row",
    borderRadius: 50,
    height: 40,
    justifyContent: "space-around",
    alignItems: "center",
    marginTop: 20,
  },

  text: {
    fontSize: 15,
    fontWeight: "900",
    textTransform: "uppercase",
    color: "#333",
    letterSpacing: 0.5,
  },
  textFollow: {
    fontSize: 10,
    fontWeight: "900",
    textTransform: "uppercase",
    color: "#ff0000",
    letterSpacing: 0.5,
    marginLeft: 5,
  },
  rateCon: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 3,
  },
  textHead: {
    fontSize: 10,
    color: "#292929",
  },
  textRate: {
    fontSize: 11,
    color: "#838383",
    textTransform: "capitalize",
  },
  bottom: {
    // width: "100%",
    // height:'100%',
    borderColor: "#dddd",
    borderWidth: 1,
  },
  bottomDetails: {
    width: "100%",
    paddingBottom: 10,
    paddingHorizontal: 20,
  },
  textHead2: {
    fontSize: 13,
    color: "#292929",
    fontWeight: "600",
  },
});
export default ShopSinglePage;
