const ProductPage = () => {
  const [product, setProduct] = useState<Product>();
  const [filter, setFilter] = useState<Product[]>();
  const [quantity, setQuantity] = useState(1);
  const location = useLocation();
  const id = location.pathname.split("/")[2];
  const dispatch = useAppDispatch();
  const handleQuantity = (type: string) => {
    if (quantity > 1 && type === "dec") setQuantity(quantity - 1);
    if (type === "inc") setQuantity(quantity + 1);
  };

  useEffect(() => {
    const getProducts = async () => {
      try {
        const res = await publicRequest.get(`/products/find/${id}`);
        setProduct(res.data);
      } catch (err) {
        console.log(err);
      }
    };
    getProducts();
  }, [id]);
  useEffect(() => {
    const getFilter = async () => {
      try {
        if (product?.color) {
          const res = await axios.get(`http://localhost:5000/api/products`);
          setFilter(res.data);
        }
      } catch (err) {
        console.log(err);
      }
    };
    getFilter();
  }, [product?.color]);
  const handleClick = () => {
    if (product)
      dispatch(
        addProduct({
          product: product,
          quantity: quantity,
        })
      );
  };
  return (
    <Container>
      {product && filter ? (
        <>
          <Navbar />
          <PromoInfo />
          <Wrapper>
            <ImageContainer>
              <Image src={product.img} />
            </ImageContainer>
            <InfoContainer>
              <Title>{product.title}</Title>
              <Description>{product?.description}</Description>
              <Price>{product.price}PLN</Price>
              <FilterContainer>
                <Filter>
                  <FilterTitle>Color</FilterTitle>
                  {filter
                    .filter((item) => item.color[0] !== product.color[0])
                    .map((item, index) => (
                      <Link key={index} to={`/product/${item._id}`}>
                        <FilterColor color={item.color[0]} />
                      </Link>
                    ))}
                </Filter>
              </FilterContainer>
              <AddContainer>
                <AmountContainer>
                  <RemoveIcon onClick={() => handleQuantity("dec")} />
                  <Amount>{quantity}</Amount>
                  <AddIcon onClick={() => handleQuantity("inc")} />
                </AmountContainer>
                <Button onClick={() => handleClick()}>Add to cart</Button>
              </AddContainer>
            </InfoContainer>
          </Wrapper>
          <Footer />
        </>
      ) : null}
    </Container>
  );
};

export default ProductPage;
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
interface Product {
  _id: string;
  title: string;
  description: string;
  img: string;
  price: number;
  color: string[];
  quantity: number;
}
interface InitialState {
  products: Product[];
  quantity: number;
  total: number;
}
const initialState: InitialState = { products: [], quantity: 0, total: 0 };
const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addProduct: (
      state,
      action: PayloadAction<{
        product: Product;
        quantity: number;
      }>
    ) => {
      state.quantity += 1;
      state.products.push(action.payload.product);
      state.total += action.payload.product.price * action.payload.quantity;
    },
  },
});
export const { addProduct } = cartSlice.actions;
export default cartSlice.reducer;