import React, { useState, useEffect, useRef } from "react";
import { useParams, Link } from "react-router-dom";
import Navbar from "./Navbar";
import Footer from "./Footer";
import "./productpage.css";
import Rating from "../imgs/rating.png";
import added from "../imgs/added.png";
import add from "../imgs/not-added.png";
import { AddToCart, RemoveCart } from "../action/Cart";
import { useSelector, useDispatch } from "react-redux";
import VanillaTilt from "vanilla-tilt";
import LowerNav from "./LowerNav";
function ProductPage() {
const { id } = useParams();
const [product, setProduct] = useState("");
const [Size, setSize] = useState("");
const [AddedIds, setAddedIds] = useState([]);
const [reviews, setReviews] = useState(null);
const Quantity = 1;
const tiltRef = useRef(null);
document.title = `${product ? product.title : "Amazon"}`
const CartItems = useSelector((state) => state.CartItemsAdded.CartItems);
const dispatch = useDispatch();
useEffect(() => {
const getProducts = async () => {
const data = await fetch(`https://fakestoreapi.com/products/${id}`);
const new_data = await data.json();
setProduct(new_data);
};
const randomNumber = Math.floor(Math.random() * 81) + 20;
setReviews(randomNumber);
getProducts();
}, [id]);
useEffect(() => {
window.scrollTo(0, 0);
}, []);
useEffect(() => {
const ids = CartItems.map((item) => item.id);
setAddedIds(ids);
}, [CartItems]);
const isAdded = (itemId) => {
return AddedIds.includes(itemId);
};
useEffect(() => {
VanillaTilt.init(tiltRef.current, {
max: 10,
speed: 100,
transition: true,
easing: "ease-out",
});
}, []);
const handleAddToCart = () => {
if (!isAdded(product.id)) {
const item = {
id: product.id,
title: product.title,
price: product.price,
image: product.image,
size: Size,
category: product.category,
quantity: Quantity,
};
dispatch(AddToCart(item));
} else {
dispatch(RemoveCart(product.id));
}
};
const handleAddToCart2 = () => {
if (!isAdded(product.id)) {
const item = {
id: product.id,
title: product.title,
price: product.price,
image: product.image,
size: Size,
category: product.category,
quantity: Quantity,
};
dispatch(AddToCart(item));
} else {
}
};
const limited = product && product.description;
// const DescLimited = limited ? limited.slice(0, 200) + "." : "";
return (
<>
{product.title}
{product.description}
{product ? `(${reviews})` : ""}
Choose a size
setSize("S")} className={`size ${Size === "S" ? "size-clicked" : ""}`} > S
setSize("M")} className={`size ${Size === "M" ? "size-clicked" : ""}`} > M
setSize("L")} className={`size ${Size === "L" ? "size-clicked" : ""}`} > L
setSize("XL")} className={`size ${Size === "XL" ? "size-clicked" : ""}`} > XL
setSize("XXL")} className={`size ${Size === "XXL" ? "size-clicked" : ""}`} > XXL
Price:
${product.price}
${Math.round(product.price * 1.66)}