771 lines
27 KiB
TypeScript
771 lines
27 KiB
TypeScript
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 (
|
|
<View style={tw`flex-1 bg-gray-50 px-2 border-r border-gray-200`}>
|
|
<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={tw`pb-20`}>
|
|
<View style={tw`flex-col gap-3`}>
|
|
{/* All Products Item */}
|
|
<MyTouchableOpacity
|
|
style={[
|
|
tw`items-center w-full mb-2 rounded-2xl overflow-hidden`,
|
|
isAllActive ? tw`shadow-lg` : tw``
|
|
]}
|
|
onPress={() => {
|
|
router.replace(allSlotsUrl as any);
|
|
}}
|
|
activeOpacity={0.8}
|
|
>
|
|
{isAllActive ? (
|
|
<LinearGradient
|
|
colors={[theme.colors.brand400, theme.colors.brand600]}
|
|
style={tw`w-full p-3 items-center`}
|
|
start={{ x: 0, y: 0 }}
|
|
end={{ x: 1, y: 1 }}
|
|
>
|
|
<View style={tw`w-10 h-10 rounded-full items-center justify-center bg-white/20 mb-1 border border-white/30`}>
|
|
<MaterialIcons name="grid-view" size={20} color="white" />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-white text-center`}>
|
|
ALL
|
|
</MyText>
|
|
</LinearGradient>
|
|
) : (
|
|
<View style={tw`w-full p-3 items-center bg-white border border-gray-100 rounded-2xl`}>
|
|
<View style={tw`w-10 h-10 rounded-full items-center justify-center bg-gray-50 mb-1`}>
|
|
<MaterialIcons name="grid-view" size={20} color="#6B7280" />
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-medium text-gray-500 text-center`}>
|
|
ALL
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
</MyTouchableOpacity>
|
|
|
|
<View style={tw`h-[1px] bg-gray-200 my-1 mx-2`} />
|
|
|
|
{/* 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 (
|
|
<MyTouchableOpacity
|
|
key={store.id}
|
|
style={[
|
|
tw`items-center w-full mb-3 rounded-2xl overflow-hidden`,
|
|
isStoreActive ? tw`shadow-lg` : tw``
|
|
]}
|
|
onPress={() => {
|
|
setStoreId(store.id);
|
|
const targetUrl = `${baseUrl}${slotId ? `?slotId=${slotId}&storeId=${store.id}` : `?storeId=${store.id}`}`;
|
|
|
|
router.replace(targetUrl as any);
|
|
}}
|
|
activeOpacity={0.8}
|
|
>
|
|
{isStoreActive ? (
|
|
<LinearGradient
|
|
colors={[theme.colors.brand400, theme.colors.brand600]}
|
|
style={tw`w-full p-2 py-3 items-center`}
|
|
start={{ x: 0, y: 0 }}
|
|
end={{ x: 1, y: 1 }}
|
|
>
|
|
<View style={tw`w-12 h-12 rounded-full items-center justify-center bg-white border-2 border-white mb-2 shadow-sm overflow-hidden`}>
|
|
{store.signedImageUrl ? (
|
|
<Image
|
|
source={{ uri: store.signedImageUrl }}
|
|
style={tw`w-12 h-12 rounded-full`}
|
|
resizeMode="cover"
|
|
/>
|
|
) : (
|
|
<MaterialIcons name="storefront" size={24} color={theme.colors.brand500} />
|
|
)}
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-bold text-white text-center w-full leading-tight`} numberOfLines={2}>
|
|
{store.name.replace(/^The\s+/i, '')}
|
|
</MyText>
|
|
|
|
{/* Active Pip/Indicator */}
|
|
<View style={tw`absolute right-0 top-0 bottom-0 w-1 bg-white/30`} />
|
|
</LinearGradient>
|
|
) : (
|
|
<View style={tw`w-full p-2 py-3 items-center bg-white border border-gray-100 rounded-2xl`}>
|
|
<View style={tw`w-12 h-12 rounded-full items-center justify-center bg-gray-50 mb-2 border border-gray-100 overflow-hidden`}>
|
|
{store.signedImageUrl ? (
|
|
<Image
|
|
source={{ uri: store.signedImageUrl }}
|
|
style={tw`w-12 h-12 rounded-full`}
|
|
resizeMode="cover"
|
|
/>
|
|
) : (
|
|
<MaterialIcons name="storefront" size={24} color="#9CA3AF" />
|
|
)}
|
|
</View>
|
|
<MyText style={tw`text-[10px] font-medium text-gray-500 text-center w-full leading-tight`} numberOfLines={2}>
|
|
{store.name.replace(/^The\s+/i, '')}
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
</MyTouchableOpacity>
|
|
);
|
|
}) || (
|
|
<MyText style={tw`text-xs text-gray-400 text-center py-4`}>Loading...</MyText>
|
|
)}
|
|
</View>
|
|
</ScrollView>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
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<any>(null);
|
|
const positions = React.useRef<number[]>([]);
|
|
|
|
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 (
|
|
<ScrollView
|
|
ref={scrollRef}
|
|
horizontal
|
|
testID={testID}
|
|
showsHorizontalScrollIndicator={false}
|
|
style={[tw`bg-white`, { flexGrow: 0, height: 48 }]}
|
|
contentContainerStyle={tw`px-2 items-center`}
|
|
>
|
|
{items.map((item, i) => {
|
|
const isActive = i === index;
|
|
return (
|
|
<MyTouchableOpacity
|
|
key={item.id}
|
|
testID={`${tabTestIDPrefix}-${item.id}`}
|
|
onLayout={(e: any) => {
|
|
positions.current[i] = e.nativeEvent.layout.x;
|
|
}}
|
|
onPress={() => onSelect(item.id)}
|
|
style={tw`h-12 px-3 justify-center`}
|
|
activeOpacity={0.7}
|
|
>
|
|
<View style={tw`items-center justify-center`}>
|
|
<MyText
|
|
style={[
|
|
tw`text-sm font-bold`,
|
|
isActive
|
|
? { color: theme.colors.brand600 }
|
|
: { color: '#64748B' },
|
|
]}
|
|
>
|
|
{item.label}
|
|
</MyText>
|
|
<View
|
|
style={[
|
|
tw`h-1 rounded-full mt-1 self-stretch`,
|
|
{
|
|
backgroundColor: isActive
|
|
? theme.colors.brand500
|
|
: 'transparent',
|
|
},
|
|
]}
|
|
/>
|
|
</View>
|
|
</MyTouchableOpacity>
|
|
);
|
|
})}
|
|
</ScrollView>
|
|
);
|
|
});
|
|
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 (
|
|
<>
|
|
<View
|
|
style={[
|
|
tw`w-full bg-white`,
|
|
isForFlashDelivery ? tw`pb-1` : tw`flex-row px-4 py-2 mb-1`,
|
|
]}
|
|
>
|
|
<QuickDeliveryAddressSelector
|
|
slotId={Number(slotId)}
|
|
onSlotChange={handleSlotChange}
|
|
isForFlashDelivery={isForFlashDelivery}
|
|
/>
|
|
</View>
|
|
{/* Flash delivery has no store rail: the tag tabs live in the products
|
|
screen and this layout only renders the child route. */}
|
|
{isForFlashDelivery ? (
|
|
<View style={tw`flex-1 bg-white`}>
|
|
<Slot />
|
|
</View>
|
|
) : (
|
|
<Drawer
|
|
drawerContent={(props) => CustomDrawerContent(baseUrl, props, slotId, storeId)}
|
|
screenOptions={{
|
|
headerShown: false,
|
|
drawerType: 'permanent',
|
|
drawerStyle: {
|
|
width: 85,
|
|
...(isDrawerHidden && { display: 'none' }),
|
|
},
|
|
headerStyle: {
|
|
// width: 220,
|
|
backgroundColor: 'white',
|
|
},
|
|
headerShadowVisible: false,
|
|
}}
|
|
>
|
|
</Drawer>
|
|
)}
|
|
|
|
{/* <FloatingCartBar /> */}
|
|
<View style={tw`absolute bottom-2 left-4 right-4`}>
|
|
<FloatingCartBar isFlashDelivery={isForFlashDelivery} />
|
|
{/* <View style={tw`h-12 w-full bg-green-600`}></View> */}
|
|
</View>
|
|
</>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<View testID={`${cartType === "flash" ? "flash-product" : "slot-product"}-${item.id}`}>
|
|
<MyTouchableOpacity
|
|
testID="compact-product-card"
|
|
style={[
|
|
tw`bg-white rounded-lg shadow-sm mb-2 overflow-hidden border border-gray-100`,
|
|
{ width: itemWidth },
|
|
]}
|
|
onPress={onPress}
|
|
activeOpacity={0.9}
|
|
>
|
|
<View style={tw`relative`}>
|
|
<Image
|
|
source={{ uri: item.images?.[0] }}
|
|
style={{ width: "100%", height: itemWidth, resizeMode: "cover" }}
|
|
/>
|
|
{isOutOfStock && (
|
|
<View style={tw`absolute inset-0 bg-black/30 items-center justify-center`}>
|
|
<MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText>
|
|
</View>
|
|
)}
|
|
<View testID={`${cartType === "flash" ? "flash-add" : "slot-add"}-${item.id}`} style={tw`absolute bottom-2 right-2`}>
|
|
{quantity > 0 ? (
|
|
<MiniQuantifier
|
|
value={quantity}
|
|
onChange={handleQuantityChange}
|
|
step={item.incrementStep}
|
|
showUnits={true}
|
|
// unit={item.unitNotation}
|
|
/>
|
|
) : (
|
|
<MyTouchableOpacity
|
|
testID="compact-card-add"
|
|
style={tw`w-8 h-8 rounded-full bg-white items-center justify-center shadow-md`}
|
|
onPress={() => handleQuantityChange(1)}
|
|
activeOpacity={0.8}
|
|
>
|
|
<CartIcon focused={false} size={16} color="#2E90FA" />
|
|
</MyTouchableOpacity>
|
|
)}
|
|
</View>
|
|
</View>
|
|
|
|
<View style={tw`p-2`}>
|
|
<MyText style={tw`text-gray-900 font-medium text-xs mb-1`} numberOfLines={2}>
|
|
{item.name}
|
|
</MyText>
|
|
|
|
<View style={tw`flex-row items-center justify-between`}>
|
|
<View style={tw`flex-row items-baseline flex-wrap`}>
|
|
<MyText style={tw`text-brand500 font-bold text-sm`}>₹{cartType === "flash" ? (item.flashPrice ?? item.price) : item.price}</MyText>
|
|
{item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
|
|
<MyText style={tw`text-gray-400 text-xs ml-1 line-through`}>₹{item.marketPrice}</MyText>
|
|
)}
|
|
{item.productType !== 'combo' && (
|
|
<MyText style={tw`text-gray-600 text-xs ml-1`}>Quantity: <MyText style={tw`text-[#f81260] font-semibold`}>{item.unit || item.unitNotation}</MyText></MyText>
|
|
)}
|
|
</View>
|
|
</View>
|
|
</View>
|
|
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
);
|
|
};
|
|
|
|
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 (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MyText style={tw`text-gray-500 font-medium`}>Loading slot delivery...</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (slotsError) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MaterialIcons name="error-outline" size={48} color="#D84343" />
|
|
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
|
|
<MyText style={tw`text-gray-500 mt-2`}>Failed to load slot delivery</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (!slot) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center`}>
|
|
<MyText style={tw`text-2xl font-bold text-gray-900 mb-4`}>Quick Delivery</MyText>
|
|
<MyText style={tw`text-gray-600`}>No delivery slot available.</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
// 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<typeof product> => product !== null && product !== undefined)
|
|
?.filter(product => !productSlotsMap[product.id]?.isOutOfStock) || [];
|
|
|
|
const filteredProducts = storeIdNum
|
|
? slotProducts.filter(p => p.storeId === storeIdNum)
|
|
: slotProducts;
|
|
|
|
return (
|
|
<View testID="slot-detail-page" style={tw`flex-1`}>
|
|
<MyFlatList
|
|
data={filteredProducts}
|
|
numColumns={2}
|
|
renderItem={({ item }) => (
|
|
<CompactProductCard
|
|
item={item}
|
|
handleAddToCart={handleAddToCart}
|
|
onPress={() => 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 ? (
|
|
<View style={tw`items-center justify-center py-10`}>
|
|
<MyText style={tw`text-gray-400 font-medium`}>No products from this store in this slot.</MyText>
|
|
</View>
|
|
) : null
|
|
}
|
|
/>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
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<number | null>(null);
|
|
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(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<number>((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) => (
|
|
<View key={item.id} style={tw`mb-3`}>
|
|
<ProductCard
|
|
item={item}
|
|
itemWidth={flashItemWidth}
|
|
cartType="flash"
|
|
variant="hero"
|
|
miniView
|
|
showDeliveryInfo={false}
|
|
useAddToCartDialog={false}
|
|
onPress={() => {
|
|
if (onProductPress) {
|
|
onProductPress(item.id);
|
|
} else {
|
|
router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${item.id}`);
|
|
}
|
|
}}
|
|
/>
|
|
</View>
|
|
);
|
|
|
|
const renderGrid = (products: any[], testID: string) => (
|
|
<View testID={testID} style={tw`flex-row flex-wrap justify-between`}>
|
|
{products.map(renderProduct)}
|
|
</View>
|
|
);
|
|
|
|
const renderShowMore = (testID: string, onPress: () => void) => (
|
|
<View style={tw`items-center py-4`}>
|
|
<MyTouchableOpacity
|
|
testID={testID}
|
|
style={tw`px-6 py-3 rounded-full bg-brand500 shadow-sm`}
|
|
activeOpacity={0.85}
|
|
onPress={onPress}
|
|
>
|
|
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText>
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
);
|
|
|
|
const renderEmpty = () => (
|
|
<View style={tw`items-center justify-center py-10`}>
|
|
<MyText style={tw`text-gray-400 font-medium`}>No 1 Hr Delivery products available.</MyText>
|
|
</View>
|
|
);
|
|
|
|
if (productsQuery?.isLoading) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MyText style={tw`text-gray-500 font-medium`}>Loading 1 Hr Delivery...</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
if (productsQuery?.error && !productsQuery?.data) {
|
|
return (
|
|
<AppContainer>
|
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
|
<MaterialIcons name="error-outline" size={48} color="#D84343" />
|
|
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
|
|
<MyText style={tw`text-gray-500 mt-2`}>Failed to load 1 Hr Delivery</MyText>
|
|
</View>
|
|
</AppContainer>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<ScrollView
|
|
style={tw`flex-1 bg-white`}
|
|
contentContainerStyle={tw`pb-24`}
|
|
refreshControl={
|
|
<RefreshControl
|
|
refreshing={productsQuery.isFetching}
|
|
onRefresh={() => {
|
|
productsQuery.refetch();
|
|
refetchStores();
|
|
}}
|
|
tintColor={theme.colors.brand500}
|
|
colors={[theme.colors.brand500]}
|
|
/>
|
|
}
|
|
>
|
|
<View style={tw`px-4 pt-2`}>
|
|
<SearchBar
|
|
testID="flash-product-search"
|
|
value={searchQuery}
|
|
onChangeText={setSearchQuery}
|
|
placeholder="Search products..."
|
|
/>
|
|
</View>
|
|
|
|
{/* Tag section — tabs scroll with the page, not sticky. */}
|
|
<FlashTabStrip
|
|
testID="flash-tag-strip"
|
|
tabTestIDPrefix="flash-tag-tab"
|
|
items={tags.map((tag: any) => ({ id: tag.id, label: tag.tagName }))}
|
|
activeId={activeTagId}
|
|
onSelect={setSelectedTagId}
|
|
/>
|
|
<View testID="flash-tag-section" style={tw`px-4`}>
|
|
{tagProducts.length > 0
|
|
? renderGrid(visibleTagProducts, 'flash-tag-grid')
|
|
: renderEmpty()}
|
|
{tagProducts.length > tagVisibleCount &&
|
|
renderShowMore('flash-products-show-more', () =>
|
|
setTagVisibleCount((count) => count + FLASH_PAGE_SIZE)
|
|
)}
|
|
</View>
|
|
|
|
{/* Shop by Store — one tab per store. */}
|
|
{stores.length > 0 && (
|
|
<View testID="flash-store-section" style={tw`mt-8`}>
|
|
<View style={tw`px-4 mb-2`}>
|
|
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>
|
|
Shop by Store
|
|
</MyText>
|
|
</View>
|
|
<FlashTabStrip
|
|
testID="flash-store-strip"
|
|
tabTestIDPrefix="flash-store-tab"
|
|
items={stores.map((store: any) => ({
|
|
id: store.id,
|
|
label: store.name.replace(/^The\s+/i, ''),
|
|
}))}
|
|
activeId={activeStoreId}
|
|
onSelect={setSelectedStoreId}
|
|
/>
|
|
<View style={tw`px-4`}>
|
|
{storeProducts.length > 0
|
|
? renderGrid(visibleStoreProducts, 'flash-store-grid')
|
|
: renderEmpty()}
|
|
{storeProducts.length > storeVisibleCount &&
|
|
renderShowMore('flash-store-show-more', () =>
|
|
setStoreVisibleCount((count) => count + FLASH_PAGE_SIZE)
|
|
)}
|
|
</View>
|
|
</View>
|
|
)}
|
|
</ScrollView>
|
|
);
|
|
}
|