import style from '../styles/item-action.module.css' import React, { useEffect, useState } from 'react' import { Spinner, Tooltip } from '@chakra-ui/react' import { MinusIcon, PlusIcon, Trash2Icon } from 'lucide-react' import { CartItem } from '~/types/cart' import { getAuth } from '~/libs/auth' import { deleteUserCart, upsertUserCart } from '~/services/cart' import { useDebounce } from 'usehooks-ts' import { useCartStore } from '../stores/useCartStore' import { useProductCartContext } from '@/contexts/ProductCartContext' type Props = { item: CartItem } const CartItemAction = ({ item }: Props) => { const auth = getAuth() const { setRefreshCart } = useProductCartContext() const [isLoadDelete, setIsLoadDelete] = useState(false) const [isLoadQuantity, setIsLoadQuantity] = useState(false) const [quantity, setQuantity] = useState(item.quantity) const { loadCart } = useCartStore() const limitQty = item.limit_qty?.transaction || 0 const handleDelete = async () => { if (typeof auth !== 'object') return setIsLoadDelete(true) await deleteUserCart(auth.id, [item.cart_id]) await loadCart(auth.id) setIsLoadDelete(false) setRefreshCart(true) } const decreaseQty = () => { setQuantity((quantity) => quantity -= 1) } const increaseQty = () => { setQuantity((quantity) => quantity += 1) } const debounceQty = useDebounce(quantity, 1000) useEffect(() => { if (isNaN(debounceQty)) setQuantity(1) if (limitQty > 0 && debounceQty > limitQty) setQuantity(limitQty) }, [debounceQty, limitQty]) useEffect(() => { const updateCart = async () => { if (typeof auth !== 'object' || isNaN(debounceQty)) return setIsLoadQuantity(true) await upsertUserCart({ userId: auth.id, type: item.cart_type, id: item.id, qty: debounceQty, selected: item.selected, }) await loadCart(auth.id) setIsLoadQuantity(false) } updateCart() //eslint-disable-next-line react-hooks/exhaustive-deps }, [debounceQty]) return (
{isLoadQuantity && (
)} setQuantity(parseInt(e.target.value))} value={quantity} /> 0 ? `Max. ${limitQty}` : ''}>
) } export default CartItemAction