"use client";
import React, { useContext, useEffect, useState } from "react";
import { Trash2, Plus } from "lucide-react";
import authAxios, { backendUrl } from "@/utils/axios";
import ProductContext from "@/app/contexts/productContext";
import EmptyCart from "./emptyCart";
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import axios from "axios";
import { useRouter } from "next/navigation";
import PaymentComponent from "../payment/paymentComponent";
import { useCurrency } from "@/app/contexts/currencyContext";
import Link from "next/link";
import Image from "next/image";
import toast from "react-hot-toast";
const ShoppingCart = () => {
const [cartItems, setCartItems] = useState(null);
const [error, setError] = useState(null);
const [shippingAddress, setShippingAddress] = useState(""); // New state for address
const router = useRouter();
const { cartFn } = useContext(ProductContext);
const { formatPrice } = useCurrency();
const getCart = async () => {
const response = await authAxios.get("/orders/cart/");
setCartItems(response.data);
};
useEffect(() => {
getCart();
}, []);
const handleQuantityChange = async (variantId, designId, quantityChange) => {
const response = await cartFn(variantId, designId, quantityChange);
console.log(response)
if (response?.status == 200) {
setCartItems((prev) => {
if (!prev) return prev;
const updatedItems = prev[0].items.map((item) => {
if (item.variant.id === variantId && item?.design?.id === designId) {
const updatedQuantity = item.quantity + quantityChange;
const updatedTotalPrice =
(item.variant.price + (item?.design?.design_price || 0)) *
updatedQuantity;
if (updatedQuantity <= 0) {
return null;
}
return {
...item,
quantity: updatedQuantity,
total_price: updatedTotalPrice,
};
}
return item;
});
const filteredItems = updatedItems.filter((item) => item !== null);
return [
{
...prev[0],
items: filteredItems,
total_amount: filteredItems.reduce(
(sum, item) => sum + item.total_price,
0
),
},
];
});
}
};
if (!cartItems) {
return null;
}
if (!cartItems[0]?.items?.length) {
return
Size: {item.variant.size.size_name}
)} {item?.design?.design_name && (Your Design: {item.design.design_name}
)}