import Link from '@/core/components/elements/Link/Link'
import useCart from '../hooks/useCart'
import Image from '@/core/components/elements/Image/Image'
import NextImage from 'next/image'
import currencyFormat from '@/core/utils/currencyFormat'
import { useEffect, useState } from 'react'
import { addCart, deleteItemCart, getCartApi, updateItemCart } from '@/core/utils/cart'
import { CheckIcon, TrashIcon } from '@heroicons/react/24/outline'
import { createSlug } from '@/core/utils/slug'
import { useRouter } from 'next/router'
import BottomPopup from '@/core/components/elements/Popup/BottomPopup'
import { toast } from 'react-hot-toast'
import Spinner from '@/core/components/elements/Spinner/Spinner'
import Alert from '@/core/components/elements/Alert/Alert'
import MobileView from '@/core/components/views/MobileView'
import DesktopView from '@/core/components/views/DesktopView'
import ProductCard from '@/lib/product/components/ProductCard'
import productSearchApi from '@/lib/product/api/productSearchApi'
import whatsappUrl from '@/core/utils/whatsappUrl'
import useAuth from '@/core/hooks/useAuth'
import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner'
import { getPromotionProgram } from '@/lib/promotinProgram/api/homepageApi'
import PromotionType from '@/lib/promotinProgram/components/PromotionType'
import { gtagBeginCheckout } from '@/core/utils/googleTag'
import { useProductCartContext } from '@/contexts/ProductCartContext'
const Cart = () => {
const router = useRouter()
const [products, setProducts] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const auth = useAuth()
const [cart, setCart] = useState(null)
const { setRefreshCart } = useProductCartContext()
useEffect(() => {
if (!auth) return
}, [auth])
const getCart = async () => {
const listCart = await getCartApi()
setCart(listCart)
}
useEffect(() => {
getCart()
}, [])
useEffect(() => {
if (cart) {
const processProducts = async () => {
const updatedProducts = await Promise.all(
cart.products.map(async (product) => {
const id = product.id
const program = await getPromotionProgram({ id })
const isPromo = program.length > 0 ? 1 : 0
return {
...product,
isPromo
}
})
)
setProducts(updatedProducts)
}
// processProducts()
setProducts(cart.products)
setIsLoading(false)
}
}, [cart])
const [totalPriceBeforeTax, setTotalPriceBeforeTax] = useState(0)
const [totalTaxAmount, setTotalTaxAmount] = useState(0)
const [totalDiscountAmount, setTotalDiscountAmount] = useState(0)
const [deleteConfirmation, setDeleteConfirmation] = useState(null)
const [productRecomendation, setProductRecomendation] = useState(null)
const [promotionType, setPromotionType] = useState(null)
const [variantId, setVariantId] = useState(null)
const [quantity, setQuantity] = useState(null)
const [promotionActiveId, setPromotionActiveId] = useState(null)
useEffect(() => {
if (!products) return
let calculateTotalPriceBeforeTax = 0
let calculateTotalTaxAmount = 0
let calculateTotalDiscountAmount = 0
for (const product of products) {
if (product.quantity == '') continue
if (!product.selected) continue
if (product.canBuy == false) {
toggleSelected(product.id)
}
let priceBeforeTax = product.price.price / 1.11
calculateTotalPriceBeforeTax += priceBeforeTax * product.quantity
calculateTotalTaxAmount += (product.price.price - priceBeforeTax) * product.quantity
calculateTotalDiscountAmount +=
(product.price.price - product.price.priceDiscount) * product.quantity
}
setTotalPriceBeforeTax(calculateTotalPriceBeforeTax)
setTotalTaxAmount(calculateTotalTaxAmount)
setTotalDiscountAmount(calculateTotalDiscountAmount)
}, [products])
useEffect(() => {
const updateData = () => {
updateItemCart({
productId: variantId,
quantity,
programLineId: promotionActiveId,
selected: true
}).then(() => {
getCart().then(() => {
if (promotionActiveId) {
setPromotionType(false)
}
})
})
}
updateData()
}, [promotionActiveId])
useEffect(() => {
const LoadProductSimilar = async () => {
const randProductIndex = Math.floor(Math.random() * products.length)
const productLoad = await productSearchApi({
query: `q=${products?.[randProductIndex].parent.name}&limit=10&operation=OR`
})
setProductRecomendation(productLoad)
}
if (products?.length > 0 && !productRecomendation) LoadProductSimilar()
}, [products, productRecomendation])
const updateQuantity = (value, productId, operation = '') => {
let productIndex = products.findIndex((product) => product.id == productId)
if (productIndex < 0) return
let productsToUpdate = products
let quantity = productsToUpdate[productIndex].quantity
if (value != '' && isNaN(parseInt(value))) return
value = value != '' ? parseInt(value) : ''
switch (operation) {
case 'PLUS':
quantity += value
break
case 'MINUS':
if (quantity - value < 1) return
quantity -= value
break
case 'BLUR':
if (value != '' && value > 0) return
quantity = 1
break
default:
quantity = value != '' && value < 1 ? 1 : value
break
}
let qty = quantity
productsToUpdate[productIndex].quantity = qty
setProducts([...productsToUpdate])
addCart(
productId,
qty,
productsToUpdate[productIndex].selected,
productsToUpdate[productIndex].program?.id
)
}
const toggleSelected = (productId) => {
let productIndex = products.findIndex((product) => product.id == productId)
if (productIndex < 0) return
let productsToUpdate = products
let isSelected = !productsToUpdate[productIndex].selected
productsToUpdate[productIndex].selected = isSelected
setProducts([...productsToUpdate])
addCart(
productId,
productsToUpdate[productIndex].quantity,
isSelected,
productsToUpdate[productIndex].program?.id
)
}
const selectedProduct = () => {
if (!products) return []
return products?.filter((product) => product?.selected == true)
}
const deleteProduct = (productId) => {
const productsToUpdate = products.filter((product) => product.id != productId)
deleteItemCart({ productId })
setDeleteConfirmation(null)
setProducts([...productsToUpdate])
setRefreshCart(true)
toast.success('Berhasil menghapus barang dari keranjang')
}
const handlePopUpPromo = (variantId, quantity, promoId = null) => {
setPromotionType(true)
setVariantId(variantId)
setQuantity(quantity)
setPromotionActiveId(promoId)
}
const handleCheckout = () => {
gtagBeginCheckout(products)
router.push('/shop/checkout')
}
const totalOrder = totalPriceBeforeTax - totalDiscountAmount + totalTaxAmount
const tax = totalOrder * 0.11
const totalPrice = totalOrder + tax
return (
<>
Keranjang
Cari Produk Lain
Keranjang
{isLoading && (
Nama Produk
Jumlah
Harga
Subtotal
Action
)}
{!isLoading && (!products || products?.length == 0) && (
)}
{products &&
products?.map((product) => (
<>
{product.hasProgram && (
Keranjang belanja anda masih kosong
)}
{product?.program?.items && (
{product.program.items.map((item) => (
<>
)}
>
))}
>
))}
Ringkasan Belanja
Produk Yang Mungkin Kamu Suka