import React from 'react'; import { View, Alert, ActivityIndicator } from 'react-native'; import { Image } from 'expo-image'; import { tw, theme, MyText, MyTouchableOpacity, Quantifier, MiniQuantifier } from 'common-ui'; import CartIcon from '@/components/icons/CartIcon'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import Ionicons from '@expo/vector-icons/Ionicons'; import dayjs from 'dayjs'; import { useGetCart, useUpdateCartItem, useRemoveFromCart, useAddToCart, } from '@/hooks/cart-query-hooks'; import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useCartStore } from '@/src/store/cartStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralProductStore } from '@/src/store/centralProductStore'; import { couponPriceFor } from '@/src/lib/product-coupons'; import { useRenderProbe } from '@/src/lib/render-probe' interface ProductCardProps { item: any; itemWidth: number; onPress?: () => void; showDeliveryInfo?: boolean; miniView?: boolean; variant?: 'default' | 'hero'; nullIfNotAvailable?: boolean; containerComp?: React.ComponentType | React.JSXElementConstructor; useAddToCartDialog?: boolean; /** Which cart this card reads and writes. Flash skips scheduled-slot logic. */ cartType?: 'regular' | 'flash'; } const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => { if (unit?.toLowerCase() === 'kg' && quantity < 1) { return { value: `${Math.round(quantity * 1000)} g`, display: `${Math.round(quantity * 1000)}g` }; } return { value: `${quantity} ${unit}(s)`, display: `${quantity}${unit}` }; }; const ProductCard: React.FC = ({ item, itemWidth, onPress, showDeliveryInfo = true, miniView = false, variant = 'default', nullIfNotAvailable = false, containerComp: ContainerComp = React.Fragment, useAddToCartDialog = false, cartType = 'regular', }) => { useRenderProbe('component:ProductCard') const isHero = variant === 'hero'; const isFlash = cartType === 'flash'; const imageUri = item.images?.[0] const [imageStatus, setImageStatus] = React.useState<'loading' | 'loaded' | 'error'>('loading') const [imageError, setImageError] = React.useState(null) const [updater, setUpdater] = React.useState(0) React.useEffect(() => { const intervalId = setInterval(() => { setUpdater(prev => prev + 1) }, 5000) return () => clearInterval(intervalId) }, []) const { data: cartData } = useGetCart({}, cartType); const { getQuickestSlot } = useProductSlotIdentifier(); const { setAddedToCartProduct } = useCartStore(); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const { addToCart = () => {} } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType) || {}; // Find current quantity from cart data const cartItem = cartData?.items?.find((cartItem: any) => cartItem.skuId === item.id); const quantity = cartItem?.quantity || 0; // Get slots data from central store const slots = useCentralSlotStore((state) => state.slots); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); // Create slot lookup map const slotMap = React.useMemo(() => { const map: Record = {}; slots?.forEach((slot: any) => { map[slot.id] = slot; }); return map; }, [slots]); // Get cart item's slot delivery time if item is in cart const cartSlot = cartItem?.slotId ? slotMap[cartItem.slotId] : null; const displayDeliveryDate = cartSlot?.deliveryTime || item.nextDeliveryDate; React.useEffect(() => { if (imageUri) { setImageStatus('loading') setImageError(null) return } setImageStatus('error') setImageError('No image available') }, [imageUri]) // Precompute the next slot and determine display out of stock status const slotId = getQuickestSlot(item.id); // Use isOutOfStock from productSlotsMap (all products now included) const productSlotInfo = productSlotsMap[item.id]; const isOutOfStockFromSlots = productSlotInfo?.isOutOfStock; const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded); // Don't treat "no slot yet" as out of stock while slot data is still loading. // Flash has no scheduled slot at all, so only the explicit flag counts. const displayIsOutOfStock = isFlash ? Boolean(isOutOfStockFromSlots) : isOutOfStockFromSlots || (isSlotsLoaded && !slotId); // Flash products carry their own promo price. const displayPrice = isFlash ? item.flashPrice ?? item.price : item.price; // Product-specific coupons land in the catalogue store; the price is derived // from the price the card actually shows, so a flash card discounts flashPrice. // Out-of-stock cards stay plain: there is nothing to buy. const couponOffers = useCentralProductStore((state) => item.id != null ? state.couponOffers[item.id] : undefined ); const couponPrice = displayIsOutOfStock ? null : couponPriceFor(couponOffers, displayPrice); // if(item.name.startsWith('Mutton Curry Cut')) { // console.log({slotId, displayIsOutOfStock}) // } // Return null if nullIfNotAvailable is true and the product is out of stock if (nullIfNotAvailable && displayIsOutOfStock) { return null; } const handleQuantityChange = (newQuantity: number) => { if (useAddToCartDialog) { setAddedToCartProduct({ productId: item.id, product: item }); } else if (newQuantity === 0 && cartItem) { removeFromCart.mutate({ itemId: cartItem.id }); } else if (newQuantity === 1 && !cartItem) { if (isFlash) { addToCart(item.id, 1, 0, () => { Alert.alert('Added to Cart', `Added ${item.name} for delivery in 1hr`); }); return; } const slotId = getQuickestSlot(item.id); if (!slotId) { Alert.alert("Error", "No available delivery slot for this product"); return; } const slot = slotMap[slotId]; const deliveryTime = slot ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A') : ''; addToCart(item.id, 1, slotId, () => { Alert.alert('Added to Cart', `Added ${item.name} for delivery at ${deliveryTime}`); }); } else if (cartItem) { updateCartItem.mutate({ itemId: cartItem.id, quantity: newQuantity }); } }; // console.log('rendering the product cart for id', item.id) return ( {/* TODO: Navigate to product detail */})} activeOpacity={0.9} > { setImageStatus('loading') setImageError(null) }} onLoad={() => setImageStatus('loaded')} onError={(event) => { setImageStatus('error') setImageError(event?.error || 'Image failed to load') }} /> {imageStatus === 'error' && ( {imageError || 'Image failed to load'} )} {displayIsOutOfStock && ( Out of Stock )} {miniView && ( {quantity > 0 ? ( ) : ( handleQuantityChange(1)} activeOpacity={0.8} > )} )} {item.name} ₹{displayPrice} {item.marketPrice && Number(item.marketPrice) > Number(displayPrice) && ( ₹{item.marketPrice} )} {couponPrice != null && ( ₹{couponPrice} With Coupon )} {item.productType !== 'combo' && ( Quantity: {item.unitNotation} )} {showDeliveryInfo && !isFlash && displayDeliveryDate && ( {dayjs(displayDeliveryDate).format("ddd, DD MMM • h:mm A")} )} {!miniView && ( <> {displayIsOutOfStock ? ( Unavailable ) : quantity > 0 ? ( ) : ( handleQuantityChange(1)} > Add to Cart )} )} ); }; // Memoised: list pages re-render their section on selection changes, and an // unmemoised card re-runs its cart/slot hooks and rebuilds its image for every // sibling. Parents pass a stable `item` and a stable `onPress`. export default React.memo(ProductCard);