bagsy/apps/mobile/app/(app)/list/[id].tsx

624 lines
16 KiB
TypeScript

import { useEffect, useState, useRef } from 'react';
import {
View,
Text,
FlatList,
Pressable,
StyleSheet,
ActivityIndicator,
Platform,
Dimensions,
Modal,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useListsStore } from '@/store/lists';
import { useStoresStore } from '@/store/stores';
import { useItemsStore } from '@/store/items';
import { useWebSocketActions } from '@/hooks/useWebSocket';
import { api } from '@/lib/api';
import type { ShoppingList, ListItem, Item, Aisle } from '@shop/types';
type SortOption = 'aisle' | 'category' | 'who-added' | 'alphabetical';
/**
* Main list screen with aisle swiper and item management
* Core shopping list UX
*/
export default function ListScreen() {
const router = useRouter();
const { id } = useLocalSearchParams<{ id: string }>();
const { lists } = useListsStore();
const { stores } = useStoresStore();
const { items } = useItemsStore();
const { notifyItemChecked, notifyItemAdded, notifyItemRemoved } = useWebSocketActions();
const [currentAisleIndex, setCurrentAisleIndex] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [sortBy, setSortBy] = useState<SortOption>('aisle');
const [showSortMenu, setShowSortMenu] = useState(false);
const [showAIModal, setShowAIModal] = useState(false);
const [selectedItemForAI, setSelectedItemForAI] = useState<(ListItem & { item?: Item }) | null>(
null
);
const [aiSuggestions, setAISuggestions] = useState<Array<{ name: string; reason: string }>>([]);
const [isLoadingAI, setIsLoadingAI] = useState(false);
const flatListRef = useRef<FlatList>(null);
const list = lists.find((l) => l.id === id);
const store = stores.find((s) => s.id === list?.storeId);
const aisles = store?.aisles || [];
const currentAisle = aisles[currentAisleIndex];
useEffect(() => {
loadListData();
}, [id]);
const loadListData = async () => {
try {
setIsLoading(true);
if (id) {
const listData = await api.get<ShoppingList>(`/api/lists/${id}`);
// Update store with fetched list
}
} catch (err) {
console.error('Failed to load list:', err);
} finally {
setIsLoading(false);
}
};
const getListItemsForAisle = (aisleId: string): (ListItem & { item?: Item })[] => {
if (!list) return [];
let filtered = list.items.map((li) => ({
...li,
item: items.find((i) => i.id === li.itemId),
}));
if (sortBy === 'aisle') {
filtered = filtered.filter((li) => li.item?.aisleId === aisleId);
} else if (sortBy === 'category') {
filtered = filtered.sort((a, b) =>
(a.item?.aisleId || '').localeCompare(b.item?.aisleId || '')
);
} else if (sortBy === 'who-added') {
filtered = filtered.sort((a, b) => a.addedBy.localeCompare(b.addedBy));
} else if (sortBy === 'alphabetical') {
filtered = filtered.sort((a, b) => (a.item?.name || '').localeCompare(b.item?.name || ''));
}
return filtered;
};
const handleCheckItem = async (listItemId: string, currentChecked: boolean) => {
if (!id || !list) return;
try {
const newChecked = !currentChecked;
// Notify other devices via WebSocket
notifyItemChecked(id, listItemId, newChecked);
// API call to update
await api.put(`/api/lists/${id}/items/${listItemId}`, {
checked: newChecked,
});
} catch (err) {
console.error('Failed to update item:', err);
}
};
const handleAisleSwipe = (index: number) => {
setCurrentAisleIndex(index);
};
const handleAddItem = () => {
router.push(`/(app)/list/${id}/add-item`);
};
const handleAIAlternatives = async (listItem: ListItem & { item?: Item }) => {
if (!listItem.item?.name) return;
try {
setIsLoadingAI(true);
setSelectedItemForAI(listItem);
setShowAIModal(true);
const response = await api.post<{ suggestions: Array<{ name: string; reason: string }> }>(
'/api/ai/suggest',
{ itemName: listItem.item.name }
);
setAISuggestions(response.suggestions);
} catch (err) {
console.error('Failed to fetch AI suggestions:', err);
setAISuggestions([]);
} finally {
setIsLoadingAI(false);
}
};
const handleSwapItem = async (newItemName: string) => {
if (!selectedItemForAI || !list || !id) return;
try {
// Search for or create the alternative item
const results = await api.get<Item[]>(
`/api/items/search?q=${encodeURIComponent(newItemName)}`
);
let alternativeItem = results[0];
if (!alternativeItem) {
// Create new item if not found
alternativeItem = await api.post<Item>('/api/items', {
name: newItemName,
});
}
// Update the list item
await api.put(`/api/lists/${id}/items/${selectedItemForAI.id}`, {
itemId: alternativeItem.id,
});
// Update local store
const updatedList = {
...list,
items: list.items.map((li) =>
li.id === selectedItemForAI.id ? { ...li, itemId: alternativeItem.id } : li
),
};
setShowAIModal(false);
} catch (err) {
console.error('Failed to swap item:', err);
}
};
if (isLoading) {
return (
<View style={styles.centerContainer}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
);
}
if (!list || !store || !currentAisle) {
return (
<View style={styles.centerContainer}>
<Text style={styles.errorText}>List or store not found</Text>
</View>
);
}
const listItems = getListItemsForAisle(currentAisle.id);
const aisleColor = currentAisle.colour || '#FF6B6B';
return (
<View style={styles.container}>
{/* Fixed gradient background */}
<LinearGradient
colors={[aisleColor, `${aisleColor}40`]}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
style={styles.gradientBackground}
/>
{/* Header with list name and sort menu */}
<View style={styles.header}>
<Pressable onPress={() => router.back()}>
<Text style={styles.backButton}>← Back</Text>
</Pressable>
<Text style={styles.title}>{list.name}</Text>
<Pressable onPress={() => setShowSortMenu(true)}>
<Text style={styles.sortButton}>⋮</Text>
</Pressable>
</View>
{/* Aisle tabs/swiper */}
<FlatList
ref={flatListRef}
data={aisles}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
scrollEventThrottle={16}
onMomentumScrollEnd={(event) => {
const index = Math.round(
event.nativeEvent.contentOffset.x / Dimensions.get('window').width
);
handleAisleSwipe(index);
}}
renderItem={({ item: aisle }) => (
<View style={{ width: Dimensions.get('window').width }}>
{/* Aisle header */}
<View style={styles.aisleHeader}>
<Text style={styles.aisleName}>{aisle.name}</Text>
<Text style={styles.itemCount}>{listItems.length} items</Text>
</View>
{/* Items list */}
<FlatList
data={listItems}
keyExtractor={(item) => item.id}
scrollEnabled={true}
renderItem={({ item: listItem }) => (
<ItemRow
listItem={listItem}
item={listItem.item}
onCheck={() => handleCheckItem(listItem.id, listItem.checked)}
onLongPress={() => handleAIAlternatives(listItem)}
/>
)}
ListEmptyComponent={<Text style={styles.emptyText}>No items in this aisle</Text>}
contentContainerStyle={styles.itemsList}
/>
</View>
)}
/>
{/* FAB to add item */}
<Pressable style={styles.fab} onPress={handleAddItem}>
<Text style={styles.fabText}>+</Text>
</Pressable>
{/* Sort menu modal */}
<Modal visible={showSortMenu} transparent animationType="fade">
<Pressable style={styles.modalOverlay} onPress={() => setShowSortMenu(false)}>
<View style={styles.sortMenu}>
<SortOption label="By Aisle" value="aisle" current={sortBy} onPress={setSortBy} />
<SortOption label="By Category" value="category" current={sortBy} onPress={setSortBy} />
<SortOption
label="By Who Added"
value="who-added"
current={sortBy}
onPress={setSortBy}
/>
<SortOption
label="Alphabetical"
value="alphabetical"
current={sortBy}
onPress={setSortBy}
/>
</View>
</Pressable>
</Modal>
{/* AI Alternatives Modal */}
<Modal visible={showAIModal} transparent animationType="fade">
<Pressable style={styles.modalOverlay} onPress={() => setShowAIModal(false)}>
<View style={styles.aiModal}>
<Text style={styles.aiTitle}>{selectedItemForAI?.item?.name}</Text>
<Text style={styles.aiSubtitle}>Alternative suggestions</Text>
{isLoadingAI ? (
<View style={styles.aiLoadingContainer}>
<ActivityIndicator size="large" color="#007AFF" />
</View>
) : (
<FlatList
data={aiSuggestions}
keyExtractor={(_, index) => index.toString()}
scrollEnabled={false}
renderItem={({ item: suggestion }) => (
<Pressable
style={styles.aiSuggestion}
onPress={() => handleSwapItem(suggestion.name)}
>
<View style={styles.aiSuggestionContent}>
<Text style={styles.aiSuggestionName}>{suggestion.name}</Text>
<Text style={styles.aiSuggestionReason}>{suggestion.reason}</Text>
</View>
</Pressable>
)}
ListEmptyComponent={<Text style={styles.aiEmpty}>No suggestions available</Text>}
/>
)}
<Pressable style={styles.aiCloseButton} onPress={() => setShowAIModal(false)}>
<Text style={styles.aiCloseButtonText}>Close</Text>
</Pressable>
</View>
</Pressable>
</Modal>
</View>
);
}
/**
* Item row component
*/
function ItemRow({
listItem,
item,
onCheck,
onLongPress,
}: {
listItem: ListItem;
item?: Item;
onCheck: () => void;
onLongPress: () => void;
}) {
return (
<Pressable
style={[styles.itemRow, listItem.checked && styles.itemRowChecked]}
onPress={onCheck}
onLongPress={onLongPress}
>
<View style={[styles.checkbox, listItem.checked && styles.checkboxChecked]}>
{listItem.checked && <Text style={styles.checkmark}>✓</Text>}
</View>
<View style={styles.itemInfo}>
<Text style={[styles.itemName, listItem.checked && styles.itemNameChecked]}>
{item?.name || 'Unknown item'}
</Text>
{listItem.quantity > 1 && <Text style={styles.quantity}>Qty: {listItem.quantity}</Text>}
</View>
</Pressable>
);
}
/**
* Sort option component
*/
function SortOption({
label,
value,
current,
onPress,
}: {
label: string;
value: SortOption;
current: SortOption;
onPress: (value: SortOption) => void;
}) {
return (
<Pressable
style={styles.sortOption}
onPress={() => {
onPress(value);
}}
>
<Text style={[styles.sortOptionText, value === current && styles.sortOptionActive]}>
{value === current ? '● ' : '○ '}
{label}
</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
centerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
gradientBackground: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 16,
paddingVertical: 12,
marginTop: Platform.OS === 'ios' ? 44 : 0,
backgroundColor: 'rgba(255, 255, 255, 0.95)',
borderBottomWidth: 1,
borderBottomColor: '#e0e0e0',
},
title: {
fontSize: 18,
fontWeight: '600',
color: '#000',
},
backButton: {
fontSize: 16,
color: '#007AFF',
},
sortButton: {
fontSize: 20,
color: '#007AFF',
},
aisleHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 16,
paddingVertical: 12,
marginTop: 80,
},
aisleName: {
fontSize: 20,
fontWeight: '700',
color: '#fff',
},
itemCount: {
fontSize: 14,
color: 'rgba(255, 255, 255, 0.8)',
},
itemsList: {
paddingHorizontal: 16,
paddingVertical: 8,
},
itemRow: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 12,
paddingHorizontal: 12,
marginVertical: 4,
backgroundColor: 'rgba(255, 255, 255, 0.9)',
borderRadius: 8,
borderLeftWidth: 4,
borderLeftColor: '#007AFF',
},
itemRowChecked: {
opacity: 0.6,
},
checkbox: {
width: 24,
height: 24,
borderRadius: 6,
borderWidth: 2,
borderColor: '#007AFF',
justifyContent: 'center',
alignItems: 'center',
marginRight: 12,
},
checkboxChecked: {
backgroundColor: '#007AFF',
},
checkmark: {
color: '#fff',
fontSize: 14,
fontWeight: 'bold',
},
itemInfo: {
flex: 1,
},
itemName: {
fontSize: 16,
fontWeight: '500',
color: '#000',
},
itemNameChecked: {
textDecorationLine: 'line-through',
color: '#999',
},
quantity: {
fontSize: 12,
color: '#666',
marginTop: 2,
},
fab: {
position: 'absolute',
bottom: 24,
right: 24,
width: 56,
height: 56,
borderRadius: 28,
backgroundColor: '#007AFF',
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
fabText: {
fontSize: 32,
color: '#fff',
fontWeight: '300',
},
emptyText: {
textAlign: 'center',
color: '#999',
fontSize: 14,
marginVertical: 24,
},
errorText: {
fontSize: 16,
color: '#FF6B6B',
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
justifyContent: 'flex-end',
},
sortMenu: {
backgroundColor: '#fff',
paddingBottom: 24,
paddingTop: 16,
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
},
sortOption: {
paddingVertical: 12,
paddingHorizontal: 16,
borderBottomWidth: 1,
borderBottomColor: '#f0f0f0',
},
sortOptionText: {
fontSize: 16,
color: '#000',
},
sortOptionActive: {
fontWeight: '600',
color: '#007AFF',
},
aiModal: {
backgroundColor: '#fff',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
paddingHorizontal: 16,
paddingTop: 20,
paddingBottom: 24,
maxHeight: '80%',
},
aiTitle: {
fontSize: 18,
fontWeight: '700',
color: '#000',
marginBottom: 4,
},
aiSubtitle: {
fontSize: 14,
color: '#666',
marginBottom: 16,
},
aiLoadingContainer: {
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 32,
},
aiSuggestion: {
paddingVertical: 12,
paddingHorizontal: 12,
marginVertical: 8,
backgroundColor: '#f9f9f9',
borderRadius: 8,
borderLeftWidth: 4,
borderLeftColor: '#10B981',
},
aiSuggestionContent: {
flex: 1,
},
aiSuggestionName: {
fontSize: 16,
fontWeight: '600',
color: '#000',
marginBottom: 2,
},
aiSuggestionReason: {
fontSize: 12,
color: '#666',
},
aiEmpty: {
textAlign: 'center',
color: '#999',
fontSize: 14,
marginVertical: 16,
},
aiCloseButton: {
marginTop: 16,
paddingVertical: 12,
backgroundColor: '#007AFF',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
},
aiCloseButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});