import React, { useEffect, useState } from 'react'; import { Helmet } from 'react-helmet'; import { useParams, Link, useNavigate } from 'react-router-dom'; import { useProductStore } from '@/store/productStore'; import { useCartStore } from '@/store/cartStore'; import { useToast } from '@/components/ui/use-toast'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { ArrowLeft, Minus, Plus, ShoppingCart, Check, Truck, ShieldCheck, RefreshCcw, AlertCircle } from 'lucide-react'; import ProductCard from '@/components/ProductCard'; import ProductVariantSelector from '@/components/ProductVariantSelector'; import { trackViewContent, trackAddToCart } from '@/lib/facebookPixel'; import { supabase } from '@/lib/supabaseClient'; import { cn } from '@/lib/utils'; const ProductDetailPage = () => { const { id } = useParams(); const navigate = useNavigate(); const { toast } = useToast(); const { fetchProductById, products, fetchProducts, fetchProductVariants } = useProductStore(); const { addItem } = useCartStore(); const [product, setProduct] = useState(null); const [variants, setVariants] = useState([]); const [selectedVariant, setSelectedVariant] = useState(null); const [quantity, setQuantity] = useState(1); const [relatedProducts, setRelatedProducts] = useState([]); const [loading, setLoading] = useState(true); // Gallery State const [galleryImages, setGalleryImages] = useState([]); const [activeImage, setActiveImage] = useState(null); useEffect(() => { let mounted = true; const loadData = async () => { if (!id) return; setLoading(true); try { const data = await fetchProductById(id); if (mounted && data) { setProduct(data); setActiveImage(data.image_url); // Default to main image trackViewContent(data); // Fetch Variants const variantData = await fetchProductVariants(id); setVariants(variantData || []); setSelectedVariant(null); // Reset selection on product change // Fetch additional images from gallery const { data: images } = await supabase .from('product_images') .select('*') .eq('product_id', id) .order('display_order', { ascending: true }); if (images) { setGalleryImages(images); } // Fetch related products (lazy load if empty) if (data.category_id && products.length === 0) { fetchProducts({ categoryId: data.category_id, itemsPerPage: 4 }); } } } catch (err) { console.error("Failed to load product details", err); } finally { if (mounted) setLoading(false); } }; loadData(); window.scrollTo(0, 0); return () => { mounted = false; }; }, [id]); // Derived state for related products useEffect(() => { if (product && products.length > 0) { const related = products .filter(p => p.category_id === product.category_id && p.id !== product.id) .slice(0, 4); setRelatedProducts(related); } }, [product, products]); // Pricing Logic (Variant vs Base) const getDisplayPrice = () => { if (selectedVariant) return selectedVariant.price; return product?.price || 0; }; const getDiscountPrice = () => { if (selectedVariant) return selectedVariant.discount_price; return product?.discount_price; }; const currentPrice = getDisplayPrice(); const discountPrice = getDiscountPrice(); const hasDiscount = discountPrice && discountPrice < currentPrice; const discountPercentage = hasDiscount ? ((currentPrice - discountPrice) / currentPrice * 100).toFixed(0) : 0; const handleBuyNow = () => { if (!product) return; // Validation: If variants exist, one MUST be selected if (variants.length > 0 && !selectedVariant) { toast({ title: "পছন্দ করুন", description: "অনুগ্রহ করে একটি ভেরিয়েন্ট (যেমন: সাইজ বা কালার) সিলেক্ট করুন।", variant: "destructive" }); return; } // Validation: Stock Check const stock = selectedVariant ? selectedVariant.stock : product.stock; if (stock < quantity) { toast({ title: "স্টক নেই", description: "দুঃখিত, এই পরিমাণ পণ্য স্টকে নেই।", variant: "destructive" }); return; } // Add quantity directly instead of loop addItem(product, selectedVariant); if(quantity > 1) { for(let i=1; i < quantity; i++) { addItem(product, selectedVariant); } } // Track AddToCart Pixel trackAddToCart(product, quantity); // Navigate directly to checkout navigate('/checkout'); }; const incrementQty = () => setQuantity(q => q + 1); const decrementQty = () => setQuantity(q => q > 1 ? q - 1 : 1); if (loading) { return (
দুঃখিত, আপনি যে পণ্যটি খুঁজছেন তা বর্তমানে অনুপলব্ধ।
{product.description}
২-৩ দিনের মধ্যে
১০০% আসল
৭ দিনের মধ্যে