import React, { useState } from 'react'; import { Drawer } from 'expo-router/drawer'; import { DrawerContentComponentProps } from '@react-navigation/drawer'; import { View, ScrollView, Alert, Dimensions, RefreshControl } from 'react-native'; import { Image } from 'expo-image'; import { useRouter, usePathname, Slot } from 'expo-router'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui'; import { trpc } from '@/src/trpc-client'; import { useAllProducts, useStores, useSlots } from '@/src/hooks/prominent-api-hooks'; import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useHideTabNav } from '@/src/hooks/useHideTabNav'; import CartIcon from '@/components/icons/CartIcon'; import ProductCard from '@/components/ProductCard'; import { useSlotStore } from '@/components/stores/slotStore'; import { LinearGradient } from 'expo-linear-gradient'; import FloatingCartBar from '@/components/floating-cart-bar'; import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'; import dayjs from 'dayjs'; const { width: screenWidth } = Dimensions.get("window"); const drawerWidth = 85; // From layout drawerStyle const itemWidth = (screenWidth - drawerWidth - 48) / 2; // Account for drawer width interface SlotLayoutProps extends SlotProductsProps { isForFlashDelivery?: boolean; } function CustomDrawerContent(baseUrl: string, drawerProps: DrawerContentComponentProps, slotIdParent?: number, storeIdParent?: number) { const router = useRouter(); const pathname = usePathname(); const { data: storesData } = useStores(); const setStoreId = useSlotStore(state => state.setStoreId); const { slotId, storeId } = useSlotStore(); // Get current pathname to determine active item const currentPath = pathname; // Check if we are on the main 'quick-delivery' page (All products) // const isAllActive = !currentPath.includes('/store/'); const isAllActive = isNaN(storeId as number); const allSlotsUrl = `${baseUrl}${slotId ? `?slotId=${slotId}` : ''}`; return ( {/* All Products Item */} { router.replace(allSlotsUrl as any); }} activeOpacity={0.8} > {isAllActive ? ( ALL ) : ( ALL )} {/* Store Items */} {storesData?.stores?.map(store => { // Check if this specific store is active const isStoreActive = storeId === store.id; // const isStoreActive = currentPath.includes(`/store/${store.id}`); return ( { setStoreId(store.id); const targetUrl = `${baseUrl}${slotId ? `?slotId=${slotId}&storeId=${store.id}` : `?storeId=${store.id}`}`; router.replace(targetUrl as any); }} activeOpacity={0.8} > {isStoreActive ? ( {store.signedImageUrl ? ( ) : ( )} {store.name.replace(/^The\s+/i, '')} {/* Active Pip/Indicator */} ) : ( {store.signedImageUrl ? ( ) : ( )} {store.name.replace(/^The\s+/i, '')} )} ); }) || ( Loading... )} ); } interface FlashTabStripProps { items: { id: number; label: string }[]; activeId: number | null; onSelect: (id: number) => void; testID: string; tabTestIDPrefix: string; } /** * Horizontally scrollable tab strip used by the 1 Hr Delivery page for both the * tag section and "Shop by Store". * * Same mechanics as the home page's TagTabStrip (plain ScrollView so Android * scrolls reliably, active tab auto-scrolled into view). It lives inside the * page's vertical ScrollView, so it scrolls away with the content. */ const FlashTabStrip = React.memo(({ items, activeId, onSelect, testID, tabTestIDPrefix, }: FlashTabStripProps) => { const scrollRef = React.useRef(null); const positions = React.useRef([]); const index = React.useMemo(() => { const idx = items.findIndex((item) => item.id === activeId); return idx < 0 ? 0 : idx; }, [items, activeId]); React.useEffect(() => { const x = positions.current[index]; if (x != null) { scrollRef.current?.scrollTo({ x: Math.max(0, x - 16), animated: true }); } }, [index]); if (items.length === 0) return null; return ( {items.map((item, i) => { const isActive = i === index; return ( { positions.current[i] = e.nativeEvent.layout.x; }} onPress={() => onSelect(item.id)} style={tw`h-12 px-3 justify-center`} activeOpacity={0.7} > {item.label} ); })} ); }); FlashTabStrip.displayName = 'FlashTabStrip'; export function SlotLayout({ slotId, storeId, baseUrl, isForFlashDelivery }: SlotLayoutProps) { const router = useRouter(); // const { slotId: paramsSlotId } = useLocalSearchParams(); const isDrawerHidden = useQuickDeliveryStore(state => state.isDrawerHidden); const setSelectedSlotId = useQuickDeliveryStore(state => state.setSelectedSlotId); const setSlotId = useSlotStore(state => state.setSlotId); const handleSlotChange = (newSlotId: number) => { setSelectedSlotId(newSlotId); setSlotId(newSlotId); router.replace(`${baseUrl}?slotId=${newSlotId}` as any); }; return ( <> {/* Flash delivery has no store rail: the tag tabs live in the products screen and this layout only renders the child route. */} {isForFlashDelivery ? ( ) : ( CustomDrawerContent(baseUrl, props, slotId, storeId)} screenOptions={{ headerShown: false, drawerType: 'permanent', drawerStyle: { width: 85, ...(isDrawerHidden && { display: 'none' }), }, headerStyle: { // width: 220, backgroundColor: 'white', }, headerShadowVisible: false, }} > )} {/* */} {/* */} ); } 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 CompactProductCard = ({ item, handleAddToCart, onPress, cartType = "regular", }: { item: any; handleAddToCart: (productId: number) => void; onPress?: () => void; cartType?: "regular" | "flash"; }) => { // Cart management for miniView const { data: cartData } = useGetCart({}, cartType); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const cartItem = cartData?.items?.find((cartItem: any) => cartItem.skuId === item.id); const quantity = cartItem?.quantity || 0; const isOutOfStock = productSlotsMap[item.id]?.isOutOfStock; const handleQuantityChange = (newQuantity: number) => { if (newQuantity === 0 && cartItem) { removeFromCart.mutate({ itemId: cartItem.id }); } else if (newQuantity === 1 && !cartItem) { handleAddToCart(item.id); } else if (cartItem) { updateCartItem.mutate({ itemId: cartItem.id, quantity: newQuantity }); } }; return ( {isOutOfStock && ( Out of Stock )} {quantity > 0 ? ( ) : ( handleQuantityChange(1)} activeOpacity={0.8} > )} {item.name} ₹{cartType === "flash" ? (item.flashPrice ?? item.price) : item.price} {item.marketPrice && Number(item.marketPrice) > Number(item.price) && ( ₹{item.marketPrice} )} {item.productType !== 'combo' && ( Quantity: {item.unit || item.unitNotation} )} ); }; interface SlotProductsProps { slotId?: number; storeId?: number; baseUrl: string; } export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseUrl, }: SlotProductsProps) { useHideTabNav('quick_delivery'); const [isLoadingDialogOpen, setIsLoadingDialogOpen] = React.useState(false); const router = useRouter(); const slotId = slotIdParent; const storeId = storeIdParent; const storeIdNum = storeId; const { data: slotsData, isLoading: slotsLoading, error: slotsError } = useSlots(); const { productsById } = useCentralProductStore(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); // Find the specific slot from cached data const slot = slotsData?.slots?.find(s => s.id === slotId); const { addToCart = () => { } } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, "regular") || {}; const handleAddToCart = (productId: number) => { setIsLoadingDialogOpen(true); const item = filteredProducts.find((p) => p.id === productId); const deliveryTime = slot?.deliveryTime ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A') : ''; addToCart(productId, 1, slotId || 0, () => { setIsLoadingDialogOpen(false); if (item) { Alert.alert('Added to Cart', `Added ${item.name} for delivery at ${deliveryTime}`); } }); }; if (slotsLoading) { return ( Loading slot delivery... ); } if (slotsError) { return ( Oops! Failed to load slot delivery ); } if (!slot) { return ( Quick Delivery No delivery slot available. ); } // Get product details from central store using slot product IDs // Filter: 1) Must exist in productsById, 2) Must not be out of stock (from slots data) const slotProducts = slot.products ?.map(p => productsById[p.id]) ?.filter((product): product is NonNullable => product !== null && product !== undefined) ?.filter(product => !productSlotsMap[product.id]?.isOutOfStock) || []; const filteredProducts = storeIdNum ? slotProducts.filter(p => p.storeId === storeIdNum) : slotProducts; return ( ( router.push(`/(drawer)/(tabs)/home/product-detail/${item.id}`)} cartType="regular" /> )} keyExtractor={(item, index) => index.toString()} columnWrapperStyle={{ gap: 16, justifyContent: 'flex-start' }} contentContainerStyle={[tw`pb-24 px-4`, { gap: 16 }]} onRefresh={() => {}} ListEmptyComponent={ storeIdNum ? ( No products from this store in this slot. ) : null } /> ); } interface FlashDeliveryProductsProps { baseUrl: string; onProductPress?: (productId: number) => void; } // 16px page margin + two 8px gaps leaves each of the three cards this wide. const flashItemWidth = (screenWidth - 48) / 3; // Three rows per page, like the home catalog. const FLASH_PAGE_SIZE = 9; export function FlashDeliveryProducts({ baseUrl, onProductPress }: FlashDeliveryProductsProps) { useHideTabNav('quick_delivery'); const [searchQuery, setSearchQuery] = useState(''); const [selectedTagId, setSelectedTagId] = useState(null); const [selectedStoreId, setSelectedStoreId] = useState(null); const [tagVisibleCount, setTagVisibleCount] = useState(FLASH_PAGE_SIZE); const [storeVisibleCount, setStoreVisibleCount] = useState(FLASH_PAGE_SIZE); const router = useRouter(); const productsQuery = useAllProducts(); const { data: storesData, refetch: refetchStores } = useStores(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const tags = productsQuery?.data?.tags || []; // First tag is the default, matching the home page. const activeTagId = selectedTagId ?? tags[0]?.id ?? null; const stores = storesData?.stores || []; // Every store gets a tab; the first is the default. const activeStoreId = selectedStoreId ?? stores[0]?.id ?? null; const trimmedQuery = searchQuery.trim().toLowerCase(); const tagProductIds = React.useMemo(() => { const tag = tags.find((t: any) => t.id === activeTagId); return new Set((tag?.productIds || []) as number[]); }, [tags, activeTagId]); const flashProducts = React.useMemo(() => { const products = productsQuery?.data?.products || []; return products.filter((p: any) => { const info = productSlotsMap[p.id]; return info?.isFlashAvailable && !info?.isOutOfStock; }); }, [productsQuery?.data?.products, productSlotsMap]); const matchesSearch = React.useCallback( (product: any) => !trimmedQuery || product.name?.toLowerCase().includes(trimmedQuery), [trimmedQuery] ); const tagProducts = React.useMemo( () => flashProducts.filter( (product: any) => (activeTagId == null || tagProductIds.has(product.id)) && matchesSearch(product) ), [flashProducts, activeTagId, tagProductIds, matchesSearch] ); const storeProducts = React.useMemo( () => flashProducts.filter( (product: any) => (activeStoreId == null || product.storeId === activeStoreId) && matchesSearch(product) ), [flashProducts, activeStoreId, matchesSearch] ); // Each section pages independently; a tab or search change starts over. React.useEffect(() => { setTagVisibleCount(FLASH_PAGE_SIZE); }, [activeTagId, trimmedQuery]); React.useEffect(() => { setStoreVisibleCount(FLASH_PAGE_SIZE); }, [activeStoreId, trimmedQuery]); const visibleTagProducts = tagProducts.slice(0, tagVisibleCount); const visibleStoreProducts = storeProducts.slice(0, storeVisibleCount); const renderProduct = (item: any) => ( { if (onProductPress) { onProductPress(item.id); } else { router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${item.id}`); } }} /> ); const renderGrid = (products: any[], testID: string) => ( {products.map(renderProduct)} ); const renderShowMore = (testID: string, onPress: () => void) => ( Show More ); const renderEmpty = () => ( No 1 Hr Delivery products available. ); if (productsQuery?.isLoading) { return ( Loading 1 Hr Delivery... ); } if (productsQuery?.error && !productsQuery?.data) { return ( Oops! Failed to load 1 Hr Delivery ); } return ( { productsQuery.refetch(); refetchStores(); }} tintColor={theme.colors.brand500} colors={[theme.colors.brand500]} /> } > {/* Tag section — tabs scroll with the page, not sticky. */} ({ id: tag.id, label: tag.tagName }))} activeId={activeTagId} onSelect={setSelectedTagId} /> {tagProducts.length > 0 ? renderGrid(visibleTagProducts, 'flash-tag-grid') : renderEmpty()} {tagProducts.length > tagVisibleCount && renderShowMore('flash-products-show-more', () => setTagVisibleCount((count) => count + FLASH_PAGE_SIZE) )} {/* Shop by Store — one tab per store. */} {stores.length > 0 && ( Shop by Store ({ id: store.id, label: store.name.replace(/^The\s+/i, ''), }))} activeId={activeStoreId} onSelect={setSelectedStoreId} /> {storeProducts.length > 0 ? renderGrid(visibleStoreProducts, 'flash-store-grid') : renderEmpty()} {storeProducts.length > storeVisibleCount && renderShowMore('flash-store-show-more', () => setStoreVisibleCount((count) => count + FLASH_PAGE_SIZE) )} )} ); }