'use client'; import { useEffect, useState } from 'react'; import { handleLineItemTimeout } from '@/lib/services/medusaCart.service'; import { StoreCartLineItem } from '@medusajs/types'; import { Timer } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@kit/ui/alert-dialog'; import { Button } from '@kit/ui/button'; const TIMEOUT_MINUTES = 15; export default function CartTimer({ cartItem, }: { cartItem: StoreCartLineItem; }) { const { t } = useTranslation(); const [timeLeft, setTimeLeft] = useState(null); const [isDialogOpen, setDialogOpen] = useState(false); const updatedAt = cartItem.updated_at!; useEffect(() => { const date = new Date(updatedAt); date.setMinutes(date.getMinutes() + TIMEOUT_MINUTES); const interval = setInterval(() => { const now = new Date(); const diff = date.getTime() - now.getTime(); setTimeLeft(diff); }, 1000); return () => clearInterval(interval); }, [updatedAt]); const minutes = timeLeft ? Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60)) : 0; const seconds = timeLeft ? Math.floor((timeLeft % (1000 * 60)) / 1000) : 0; const isTimeLeftPositive = timeLeft === null || timeLeft > 0; useEffect(() => { if (!isTimeLeftPositive) { void handleLineItemTimeout({ lineItem: cartItem, }); setDialogOpen(true); } }, [isTimeLeftPositive, cartItem.id]); if (timeLeft === null) { return
; } return ( <>
{t('cart:checkout.timeoutTitle')} {t('cart:checkout.timeoutDescription', { productTitle: cartItem.product?.title, })} setDialogOpen(false)}> {t('cart:checkout.timeoutAction')} ); }