337 lines
12 KiB
TypeScript
337 lines
12 KiB
TypeScript
'use client';
|
|
import ProductBanner from '@/assets/product.png';
|
|
import { cart_api } from '@/features/cart/lib/api';
|
|
import { BASE_URL } from '@/shared/config/api/URLs';
|
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
|
import { useCartId } from '@/shared/hooks/cartId';
|
|
import formatPrice from '@/shared/lib/formatPrice';
|
|
import { Button } from '@/shared/ui/button';
|
|
import { Input } from '@/shared/ui/input';
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { AxiosError } from 'axios';
|
|
import {
|
|
ArrowLeft,
|
|
CreditCard,
|
|
Minus,
|
|
Plus,
|
|
ShoppingBag,
|
|
Trash,
|
|
Truck,
|
|
} from 'lucide-react';
|
|
import { useTranslations } from 'next-intl';
|
|
import Image from 'next/image';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import { toast } from 'sonner';
|
|
|
|
const CartPage = () => {
|
|
const { cart_id } = useCartId();
|
|
const queryClient = useQueryClient();
|
|
const router = useRouter();
|
|
const t = useTranslations();
|
|
|
|
const { data: cartItems, isLoading } = useQuery({
|
|
queryKey: ['cart_items', cart_id],
|
|
queryFn: () => cart_api.get_cart_items(cart_id!),
|
|
enabled: !!cart_id,
|
|
select: (data) => data.data.cart_item,
|
|
});
|
|
|
|
const [quantities, setQuantities] = useState<Record<string, number>>({});
|
|
const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});
|
|
|
|
// Initial state
|
|
useEffect(() => {
|
|
if (!cartItems) return;
|
|
const initialQuantities: Record<string, number> = {};
|
|
cartItems.forEach((item) => {
|
|
initialQuantities[item.id] = item.quantity;
|
|
debounceRef.current[item.id] = null;
|
|
});
|
|
setQuantities(initialQuantities);
|
|
}, [cartItems]);
|
|
|
|
// Update cart item mutation
|
|
const { mutate: updateCartItem } = useMutation({
|
|
mutationFn: ({
|
|
body,
|
|
cart_item_id,
|
|
}: {
|
|
body: { quantity: number };
|
|
cart_item_id: string;
|
|
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
|
onSuccess: (_, variables) => {
|
|
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
|
|
|
const item = cartItems?.find(
|
|
(i) => String(i.id) === variables.cart_item_id,
|
|
);
|
|
if (item) {
|
|
const measurementName = item.product.meansurement?.name || null;
|
|
toast.success(
|
|
`${t('Miqdor')} ${variables.body.quantity} ${measurementName || 'шт.'} ${t('ga yangilandi')}`,
|
|
{ richColors: true, position: 'top-center' },
|
|
);
|
|
}
|
|
},
|
|
onError: (err: AxiosError) =>
|
|
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
|
});
|
|
|
|
// Delete cart item mutation
|
|
const { mutate: deleteCartItem } = useMutation({
|
|
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
|
cart_api.delete_cart_item(cart_item_id),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
|
toast.success(t("Savatdan o'chirildi"), {
|
|
richColors: true,
|
|
position: 'top-center',
|
|
});
|
|
},
|
|
onError: (err: AxiosError) =>
|
|
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
|
});
|
|
|
|
const handleCheckout = () => router.push('/cart/order');
|
|
|
|
if (isLoading)
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center">
|
|
Loading...
|
|
</div>
|
|
);
|
|
|
|
if (!cartItems || cartItems.length === 0)
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center">
|
|
<div className="text-center">
|
|
<ShoppingBag className="w-24 h-24 text-gray-300 mx-auto mb-4" />
|
|
<h2 className="text-2xl font-bold text-gray-800 mb-2">
|
|
{t("Savatingiz bo'sh")}
|
|
</h2>
|
|
<p className="text-gray-600 mb-6">
|
|
{t("Mahsulotlar qo'shish uchun katalogga o'ting")}
|
|
</p>
|
|
<button
|
|
onClick={() => router.push('/')}
|
|
className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition flex items-center gap-2 mx-auto"
|
|
>
|
|
<ArrowLeft className="w-5 h-5" /> {t('Xarid qilishni boshlash')}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
|
|
const subtotal =
|
|
cartItems.reduce((sum, item) => {
|
|
if (!item.product.prices.length) return sum;
|
|
const maxPrice = Math.max(
|
|
...item.product.prices.map((p) => Number(p.price)),
|
|
);
|
|
return sum + maxPrice * (quantities[item.id] || item.quantity);
|
|
}, 0) || 0;
|
|
|
|
const handleQuantityChange = (
|
|
itemId: number,
|
|
delta: number = 0,
|
|
newValue?: number,
|
|
) => {
|
|
setQuantities((prev) => {
|
|
const item = cartItems?.find((i) => i.id === Number(itemId));
|
|
if (!item) return prev;
|
|
|
|
const isGram = item.product.meansurement?.name?.toLowerCase() === 'gr';
|
|
const STEP = isGram ? 100 : 1;
|
|
const MIN_QTY = isGram ? 100 : 1;
|
|
|
|
let updatedQty;
|
|
|
|
if (newValue !== undefined) {
|
|
// Input'dan kiritilgan qiymat - minimal limitni qo'llash shart emas
|
|
updatedQty = newValue;
|
|
} else {
|
|
// +/- tugmalar bosilganda - STEP qo'llash va minimal limit
|
|
updatedQty = (prev[itemId] ?? MIN_QTY) + delta * STEP;
|
|
if (updatedQty < MIN_QTY) updatedQty = MIN_QTY;
|
|
}
|
|
|
|
// Debounce server update
|
|
if (debounceRef.current[itemId])
|
|
clearTimeout(debounceRef.current[itemId]!);
|
|
debounceRef.current[itemId] = setTimeout(() => {
|
|
if (updatedQty <= 0)
|
|
deleteCartItem({ cart_item_id: itemId.toString() });
|
|
else
|
|
updateCartItem({
|
|
body: { quantity: updatedQty },
|
|
cart_item_id: itemId.toString(),
|
|
});
|
|
}, 500);
|
|
|
|
return { ...prev, [itemId]: updatedQty };
|
|
});
|
|
};
|
|
|
|
return (
|
|
<div className="custom-container mb-6">
|
|
<div className="mb-6">
|
|
<h1 className="text-3xl font-bold text-gray-800 mb-2">{t('Savat')}</h1>
|
|
<p className="text-gray-600">
|
|
{cartItems.length} {t('ta mahsulot')}
|
|
</p>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
|
<div className="lg:col-span-2">
|
|
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
|
{cartItems.map((item, index) => {
|
|
const measurementDisplay =
|
|
item.product.meansurement?.name || 'шт.';
|
|
return (
|
|
<div
|
|
key={item.id}
|
|
className={`p-6 flex relative gap-4 ${index !== cartItems.length - 1 ? 'border-b' : ''}`}
|
|
>
|
|
<Button
|
|
variant="destructive"
|
|
size="icon"
|
|
onClick={() =>
|
|
deleteCartItem({ cart_item_id: String(item.id) })
|
|
}
|
|
className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
|
|
>
|
|
<Trash className="size-4" />
|
|
</Button>
|
|
|
|
<div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
|
|
<Image
|
|
src={
|
|
item.product.images.length > 0
|
|
? item.product.images[0].image.includes(BASE_URL)
|
|
? item.product.images[0].image
|
|
: BASE_URL + item.product.images[0].image
|
|
: ProductBanner
|
|
}
|
|
alt={item.product.name}
|
|
width={500}
|
|
height={500}
|
|
unoptimized
|
|
className="object-cover"
|
|
style={{ width: '100%', height: '100%' }}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex-1">
|
|
<h3 className="font-semibold text-lg mb-1">
|
|
{item.product.name}
|
|
</h3>
|
|
<div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
|
<span className="text-blue-600 font-bold text-xl">
|
|
{formatPrice(
|
|
Math.max(
|
|
...item.product.prices.map((p) => Number(p.price)),
|
|
),
|
|
true,
|
|
)}
|
|
</span>
|
|
<span className="text-sm text-gray-500">
|
|
/{measurementDisplay}
|
|
</span>
|
|
</div>
|
|
|
|
<p className="text-sm text-gray-500 mb-2">
|
|
{t('Miqdor')}: {quantities[item.id]} {measurementDisplay}
|
|
</p>
|
|
|
|
<div className="flex items-center border border-gray-300 rounded-lg w-max">
|
|
<button
|
|
onClick={() => handleQuantityChange(item.id, -1)}
|
|
className="p-2 cursor-pointer transition rounded-lg hover:bg-gray-50"
|
|
>
|
|
<Minus className="w-4 h-4" />
|
|
</button>
|
|
|
|
<div className="flex items-center gap-1 px-2">
|
|
<Input
|
|
value={quantities[item.id] || ''}
|
|
onChange={(e) => {
|
|
const cleaned = e.target.value.replace(/\D/g, '');
|
|
const val = cleaned === '' ? 0 : Number(cleaned);
|
|
handleQuantityChange(item.id, 0, val);
|
|
}}
|
|
type="text"
|
|
className="w-14 text-center border-none p-0"
|
|
/>
|
|
<span className="text-xs text-gray-500 whitespace-nowrap">
|
|
{measurementDisplay}
|
|
</span>
|
|
</div>
|
|
|
|
<button
|
|
onClick={() => handleQuantityChange(item.id, 1)}
|
|
className="p-2 cursor-pointer transition rounded-lg hover:bg-gray-50"
|
|
>
|
|
<Plus className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="lg:col-span-1">
|
|
<div className="bg-white rounded-lg shadow-md p-6 sticky top-4">
|
|
<h3 className="text-xl font-bold mb-4">{t('Buyurtma haqida')}</h3>
|
|
|
|
<div className="space-y-3 mb-4">
|
|
<div className="flex justify-between text-gray-600">
|
|
<span>{t('Mahsulotlar narxi')}:</span>
|
|
<span>{formatPrice(subtotal, true)}</span>
|
|
</div>
|
|
|
|
<div className="flex justify-between text-gray-600">
|
|
<span className="flex items-center gap-1">
|
|
<Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
|
|
</span>
|
|
<span>
|
|
<span className="text-green-600 font-semibold">
|
|
{t('Bepul')}
|
|
</span>
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="border-t pt-4 mb-6">
|
|
<div className="flex justify-between items-center">
|
|
<span className="text-lg font-semibold">{t('Jami')}:</span>
|
|
<span className="text-2xl font-bold text-blue-600">
|
|
{formatPrice(subtotal, true)}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<button
|
|
onClick={handleCheckout}
|
|
className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold hover:bg-blue-700 transition flex items-center justify-center gap-2 mb-4"
|
|
>
|
|
<CreditCard className="w-5 h-5" />{' '}
|
|
{t('Buyurtmani rasmiylashtirish')}
|
|
</button>
|
|
|
|
<button
|
|
onClick={() => router.push('/')}
|
|
className="w-full border-2 border-gray-300 cursor-pointer text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
|
|
>
|
|
<ArrowLeft className="w-5 h-5" /> {t('Xaridni davom ettirish')}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default CartPage;
|