This commit is contained in:
Samandar Turgunboyev
2026-01-24 16:46:02 +05:00
parent 1f77cc360d
commit ecc0029322
24 changed files with 632 additions and 563 deletions

View File

@@ -5,7 +5,6 @@ import { product_api } from '@/shared/config/api/product/api';
import { BASE_URL } from '@/shared/config/api/URLs';
import { useCartId } from '@/shared/hooks/cartId';
import formatPrice from '@/shared/lib/formatPrice';
import { Card } from '@/shared/ui/card';
import {
Carousel,
CarouselContent,
@@ -27,432 +26,284 @@ import { toast } from 'sonner';
const ProductDetail = () => {
const t = useTranslations();
const [quantity, setQuantity] = useState<number>(1);
const { product } = useParams();
const { product } = useParams<{ product: string }>();
const queryClient = useQueryClient();
const [selectedImage, setSelectedImage] = useState<number>(0);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
const { cart_id } = useCartId();
const [quantity, setQuantity] = useState(1);
const [selectedImage, setSelectedImage] = useState(0);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
/* ---------------- CART ITEMS ---------------- */
const { data: cartItems } = useQuery({
queryKey: ['cart_items', cart_id],
queryFn: () => cart_api.get_cart_items(cart_id!),
enabled: !!cart_id,
});
/* ---------------- PRODUCT DETAIL ---------------- */
const { data, isLoading } = useQuery({
queryKey: ['product_detail', product],
queryFn: () => {
if (product) return product_api.detail(product.toString());
},
select(data) {
return data?.data;
},
queryFn: () => product_api.detail(product),
select: (res) => res.data,
enabled: !!product,
});
const { data: recomendation, isLoading: proLoad } = useQuery({
/* ---------------- RECOMMENDATION ---------------- */
const { data: recomendation, isLoading: recLoad } = useQuery({
queryKey: ['product_list'],
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
select(data) {
return data.data.results;
},
select: (res) => res.data.results,
});
/* ---------------- PRICE ---------------- */
const price = Number(data?.prices?.[0]?.price || 0);
/* ---------------- SYNC CART QUANTITY ---------------- */
useEffect(() => {
if (!data || !cartItems) return;
const item = cartItems?.data.cart_item.find(
(item) => Number(item.product.id) === data?.id,
const item = cartItems.data.cart_item.find(
(i) => Number(i.product.id) === data.id,
);
if (item) {
setQuantity(item.quantity);
} else {
setQuantity(1);
}
setQuantity(item ? item.quantity : 1);
}, [data, cartItems]);
/* ---------------- DEBOUNCE UPDATE ---------------- */
useEffect(() => {
if (!cart_id || !data || !cartItems) return;
if (quantity <= 0) return;
if (!cart_id || !data || !cartItems || quantity <= 0) return;
const cartItem = cartItems?.data?.cart_item.find(
(item) => Number(item.product.id) === data?.id,
const cartItem = cartItems.data.cart_item.find(
(i) => Number(i.product.id) === data.id,
);
if (!cartItem) return;
if (cartItem.quantity === quantity) return;
if (!cartItem || cartItem.quantity === quantity) return;
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
updateCartItem({
body: { quantity },
cart_item_id: cartItem.id.toString(),
body: { quantity },
});
}, 500);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [quantity, cart_id, data, cartItems]);
}, [quantity]);
const { mutate } = useMutation({
/* ---------------- ADD TO CART ---------------- */
const { mutate: addToCart } = useMutation({
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
cart_api.cart_item(body),
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['cart_items'] });
toast.success(t("Mahsulot savatga qo'shildi"), {
richColors: true,
position: 'top-center',
});
toast.success(t("Mahsulot savatga qo'shildi"), { richColors: true });
},
onError: (err: AxiosError) => {
const detail = (err.response?.data as { detail: string }).detail;
toast.error(detail || err.message, {
richColors: true,
position: 'top-center',
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg = (err.response?.data as any)?.detail || err.message;
toast.error(msg, { richColors: true });
},
});
const { mutate: updateCartItem } = useMutation({
mutationFn: ({
body,
cart_item_id,
}: {
body: { quantity: number };
mutationFn: (payload: {
cart_item_id: string;
}) => cart_api.update_cart_item({ body, cart_item_id }),
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['cart_items'] });
},
onError: (err: AxiosError) => {
toast.error(err.message, { richColors: true, position: 'top-center' });
},
body: { quantity: number };
}) => cart_api.update_cart_item(payload),
onSuccess: () => queryClient.refetchQueries({ queryKey: ['cart_items'] }),
});
/* ---------------- FAVOURITE ---------------- */
const favouriteMutation = useMutation({
mutationFn: (productId: string) => product_api.favourite(productId),
mutationFn: (id: string) => product_api.favourite(id),
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['product_list'] });
queryClient.refetchQueries({ queryKey: ['product_detail', product] });
queryClient.invalidateQueries({ queryKey: ['product_detail'] });
queryClient.invalidateQueries({ queryKey: ['product_list'] });
},
});
const handleQuantityChange = (type: string) => {
if (type === 'increase') {
setQuantity(quantity + 1);
} else if (type === 'decrease' && quantity > 1) {
setQuantity(quantity - 1);
}
};
/* ---------------- HANDLERS ---------------- */
const handleAddToCart = () => {
if (!data || !cart_id) return;
const cartItem = cartItems?.data.cart_item.find(
(e) => Number(e.product.id) === data.id,
(i) => Number(i.product.id) === data.id,
);
if (cartItem) {
updateCartItem({
body: { quantity: quantity },
cart_item_id: cartItem.id.toString(),
body: { quantity },
});
} else {
mutate({
addToCart({
product: String(data.id),
cart: cart_id,
quantity: quantity,
quantity,
});
}
};
/* ---------------- LOADING ---------------- */
if (isLoading) {
return (
<div className="custom-container pb-5">
<div className="w-full max-w-4xl space-y-6">
<div className="h-[400px] bg-gray-100 animate-pulse rounded-lg"></div>
<div className="h-8 bg-gray-100 animate-pulse rounded w-3/4"></div>
<div className="h-6 bg-gray-100 animate-pulse rounded w-1/4"></div>
<div className="h-4 bg-gray-100 animate-pulse rounded w-full"></div>
<div className="h-4 bg-gray-100 animate-pulse rounded w-5/6"></div>
<div className="flex gap-4 mt-4">
<div className="h-10 bg-gray-100 animate-pulse rounded flex-1"></div>
<div className="h-10 bg-gray-100 animate-pulse rounded w-12"></div>
</div>
</div>
<div className="custom-container py-6">
<Skeleton className="h-[400px] w-full rounded-lg" />
</div>
);
}
/* ===================== RENDER ===================== */
return (
<div className="custom-container pb-5">
<div className="">
<div className="bg-white rounded-lg shadow-md p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<div>
<div className="relative rounded-lg overflow-hidden mb-4">
{data && (
<Image
width={500}
height={500}
src={
data.images.length > 0
? data.images[selectedImage].image
: data.image || '/placeholder.svg'
}
alt={data.name}
className="w-full h-[400px] object-contain"
/>
)}
</div>
<div className="custom-container pb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 bg-white p-6 rounded-lg shadow">
{/* IMAGES */}
<div>
<Image
width={500}
height={500}
src={
data && data?.images?.length !== 0
? BASE_URL + data.images[selectedImage]?.image
: data?.images[selectedImage]?.image
? BASE_URL + data.images[selectedImage]?.image
: '/placeholder.svg'
}
alt={data?.name || 'logo'}
className="w-full h-[400px] object-contain"
/>
<Carousel
opts={{
align: 'start',
dragFree: true,
}}
className="w-full"
>
<CarouselContent className="-ml-2 pr-[15%] sm:pr-0">
{data && data.images.length > 0 ? (
data.images.map((img, index) => (
<CarouselItem
key={img.id}
className="pl-2 basis-1/3 sm:basis-1/4 md:basis-1/5 lg:basis-1/6"
>
<button
onClick={() => setSelectedImage(index)}
className={`aspect-square w-full rounded-lg border-2 overflow-hidden transition ${
selectedImage === index
? 'border-blue-500'
: 'border-gray-200 hover:border-blue-300'
}`}
>
<Image
src={
img.image.includes(BASE_URL)
? img.image
: BASE_URL + img.image || '/placeholder.svg'
}
alt={BASE_URL + data?.image}
width={150}
height={150}
className="w-full h-full object-contain"
/>
</button>
</CarouselItem>
))
) : (
<CarouselItem className="pl-2 basis-1/3 sm:basis-1/4 md:basis-1/5 lg:basis-1/6">
<button
className={`aspect-square w-full rounded-lg border-2 overflow-hidden transition ${'border-blue-500'}`}
>
<Image
src={
data?.image.includes(BASE_URL)
? data.image
: BASE_URL + data?.image || '/placeholder.svg'
}
alt={BASE_URL + data?.image}
width={150}
height={150}
className="w-full h-full object-contain"
/>
</button>
</CarouselItem>
)}
</CarouselContent>
</Carousel>
</div>
{/* Product Info */}
<div>
<h1 className="text-3xl font-bold text-gray-800 mb-2">
{data?.name}
</h1>
{/* Price */}
<div className="mb-6">
<div className="flex items-center gap-3 max-lg:flex-col max-lg:items-start">
<span className="text-4xl font-bold text-blue-600">
{data && formatPrice(data.price, true)}
</span>
</div>
</div>
{/* Description */}
<p className="text-gray-600 mb-6">{data?.description}</p>
{/* Quantity Selector */}
<div className="mb-6">
<label className="text-gray-700 font-medium mb-2 block">
{t('Miqdor')}:
</label>
<div className="flex items-center gap-4 max-lg:flex-col max-lg:items-start">
<div className="flex items-center border border-gray-300 rounded-lg">
<button
onClick={() => handleQuantityChange('decrease')}
className="p-3 hover:bg-gray-100 transition rounded-lg"
disabled={quantity <= 1}
>
<Minus className="w-5 h-5" />
</button>
<Input
value={quantity}
onChange={(e) => {
const v = e.target.value;
if (!/^\d*$/.test(v)) return;
const num = Number(v);
if (num > 0) {
setQuantity(num);
}
}}
inputMode="numeric"
className="w-14 h-12 border-none text-center text-sm !p-0 focus-visible:ring-0"
/>
<button
onClick={() => handleQuantityChange('increase')}
className="p-3 hover:bg-gray-100 transition rounded-lg"
>
<Plus className="w-5 h-5" />
</button>
</div>
<span className="text-gray-600">
{t('Jami')}:{' '}
<span className="font-bold text-lg">
{data && formatPrice(data.price * quantity, true)}
</span>
</span>
</div>
</div>
{/* Action Buttons */}
<div className="flex gap-4 mb-6">
<button
onClick={handleAddToCart}
className="flex-1 py-4 rounded-lg cursor-pointer font-semibold text-white flex items-center justify-center gap-2 transition bg-green-600 hover:bg-green-700"
>
<ShoppingCart className="w-5 h-5" />
{t('Savatga')}
</button>
<button
onClick={() => {
if (product) {
favouriteMutation.mutate(product.toString());
}
}}
disabled={favouriteMutation.isPending}
className={`p-4 rounded-lg border-2 transition ${
data?.liked
? 'border-red-500 bg-red-50'
: 'border-gray-300 hover:border-red-500'
}`}
>
<Heart
className={`w-6 h-6 ${
data?.liked
? 'fill-red-500 text-red-500'
: 'text-gray-600'
<Carousel className="mt-4">
<CarouselContent>
{data?.images?.map((img, i) => (
<CarouselItem key={img.id} className="basis-1/4">
<button
onClick={() => setSelectedImage(i)}
className={`border rounded-lg p-1 ${
i === selectedImage
? 'border-blue-500'
: 'border-gray-200'
}`}
/>
</button>
</div>
{/* Features */}
<div className="grid grid-cols-2 gap-4 border-t pt-6">
<div className="flex flex-col items-center text-center">
<Truck className="w-8 h-8 text-blue-600 mb-2" />
<span className="text-sm text-gray-600">
{t('Bepul yetkazib berish')}
</span>
</div>
<div className="flex flex-col items-center text-center">
<Shield className="w-8 h-8 text-blue-600 mb-2" />
<span className="text-sm text-gray-600">{t('Kafolat')}</span>
</div>
</div>
</div>
</div>
</div>
{/* Specifications */}
<div className="bg-white rounded-lg shadow-md p-6 mb-8">
<h2 className="text-2xl font-bold mb-4">{t('Xususiyatlari')}</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex justify-between border-b pb-2 gap-4">
<span className="text-gray-600">{t('Qadoq turi')}:</span>
<span className="font-semibold text-right">
{data?.unity.name}
</span>
</div>
{data?.brand && (
<div className="flex justify-between border-b pb-2 gap-4">
<span className="text-gray-600">{t('Brandi')}:</span>
<span className="font-semibold text-right">{data?.brand}</span>
</div>
)}
{data?.manufacturer && (
<div className="flex justify-between border-b pb-2 gap-4">
<span className="text-gray-600">
{t('Ishlab chiqaruvchi')}:
</span>
<span className="font-semibold text-right">
{data?.manufacturer}
</span>
</div>
)}
{data?.volume && (
<div className="flex justify-between border-b pb-2 gap-4">
<span className="text-gray-600">{t('Hajmi')}:</span>
<span className="font-semibold text-right">{data?.volume}</span>
</div>
)}
</div>
</div>
{/* Related Products */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-2xl font-bold mb-6">
{t("O'xshash mahsulotlar")}
</h2>
<Carousel className="w-full">
<CarouselContent className="pr-[12%] sm:pr-0">
{proLoad &&
Array.from({ length: 6 }).map((__, index) => (
<CarouselItem
key={index}
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
>
<Card className="p-3 space-y-3 rounded-xl">
<Skeleton className="h-40 sm:h-48 md:h-56 w-full rounded-lg" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<Skeleton className="h-10 w-full rounded-lg" />
</Card>
</CarouselItem>
))}
{recomendation &&
!proLoad &&
recomendation
.filter((product) => product.state === 'A')
.map((product) => (
<CarouselItem
key={product.id}
className="basis-1/2 sm:basis-1/3 md:basis-1/3 lg:basis-1/5 xl:basis-1/6 pb-2"
>
<ProductCard product={product} />
</CarouselItem>
))}
<Image
src={BASE_URL + img.image}
alt=""
width={120}
height={120}
className="object-contain"
/>
</button>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious className="hidden lg:flex -top-12 right-12 w-9 h-9 bg-blue-600 text-white border-0" />
<CarouselNext className="hidden lg:flex -top-12 right-0 w-9 h-9 bg-blue-600 text-white border-0" />
</Carousel>
</div>
{/* INFO */}
<div>
<h1 className="text-3xl font-bold mb-2">{data?.name}</h1>
<div className="text-4xl font-bold text-blue-600 mb-4">
{formatPrice(price, true)}
</div>
<p className="text-gray-600 mb-6">{data?.short_name}</p>
{/* QUANTITY */}
<div className="flex items-center gap-4 mb-6">
<button
onClick={() => setQuantity((q) => Math.max(1, q - 1))}
className="p-2 border rounded"
>
<Minus />
</button>
<Input
value={quantity}
onChange={(e) => {
const v = Number(e.target.value);
if (v > 0) setQuantity(v);
}}
className="w-16 text-center"
/>
<button
onClick={() => setQuantity((q) => q + 1)}
className="p-2 border rounded"
>
<Plus />
</button>
</div>
<div className="mb-6 font-semibold">
{t('Jami')}: {formatPrice(price * quantity, true)}
</div>
{/* ACTIONS */}
<div className="flex gap-3">
<button
onClick={handleAddToCart}
className="flex-1 bg-green-600 hover:bg-green-700 text-white py-3 rounded-lg flex justify-center items-center gap-2"
>
<ShoppingCart />
{t('Savatga')}
</button>
<button
onClick={() => favouriteMutation.mutate(product)}
className={`p-3 rounded-lg border ${
data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300'
}`}
>
<Heart
className={data?.liked ? 'fill-red-500 text-red-500' : ''}
/>
</button>
</div>
{/* FEATURES */}
<div className="grid grid-cols-2 gap-4 mt-6 border-t pt-4">
<div className="text-center">
<Truck className="mx-auto mb-1" />
{t('Bepul yetkazib berish')}
</div>
<div className="text-center">
<Shield className="mx-auto mb-1" />
{t('Kafolat')}
</div>
</div>
</div>
</div>
{/* RELATED */}
<div className="mt-10 bg-white p-6 rounded-lg shadow">
<h2 className="text-2xl font-bold mb-4">{t("O'xshash mahsulotlar")}</h2>
<Carousel>
<CarouselContent>
{recLoad &&
Array.from({ length: 6 }).map((_, i) => (
<CarouselItem key={i} className="basis-1/5">
<Skeleton className="h-60 w-full" />
</CarouselItem>
))}
{recomendation
?.filter((p) => p.state === 'A')
.map((p) => (
<CarouselItem key={p.id} className="basis-1/5">
<ProductCard product={p} />
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>
</div>
</div>
);