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('aisle'); const [showSortMenu, setShowSortMenu] = useState(false); const [showAIModal, setShowAIModal] = useState(false); const [selectedItemForAI, setSelectedItemForAI] = useState<(ListItem & { item?: Item }) | null>( null ); const [aiSuggestions, setAISuggestions] = useState>([]); const [isLoadingAI, setIsLoadingAI] = useState(false); const flatListRef = useRef(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(`/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( `/api/items/search?q=${encodeURIComponent(newItemName)}` ); let alternativeItem = results[0]; if (!alternativeItem) { // Create new item if not found alternativeItem = await api.post('/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 ( ); } if (!list || !store || !currentAisle) { return ( List or store not found ); } const listItems = getListItemsForAisle(currentAisle.id); const aisleColor = currentAisle.colour || '#FF6B6B'; return ( {/* Fixed gradient background */} {/* Header with list name and sort menu */} router.back()}> ← Back {list.name} setShowSortMenu(true)}> ⋮ {/* Aisle tabs/swiper */} { const index = Math.round( event.nativeEvent.contentOffset.x / Dimensions.get('window').width ); handleAisleSwipe(index); }} renderItem={({ item: aisle }) => ( {/* Aisle header */} {aisle.name} {listItems.length} items {/* Items list */} item.id} scrollEnabled={true} renderItem={({ item: listItem }) => ( handleCheckItem(listItem.id, listItem.checked)} onLongPress={() => handleAIAlternatives(listItem)} /> )} ListEmptyComponent={No items in this aisle} contentContainerStyle={styles.itemsList} /> )} /> {/* FAB to add item */} + {/* Sort menu modal */} setShowSortMenu(false)}> {/* AI Alternatives Modal */} setShowAIModal(false)}> {selectedItemForAI?.item?.name} Alternative suggestions {isLoadingAI ? ( ) : ( index.toString()} scrollEnabled={false} renderItem={({ item: suggestion }) => ( handleSwapItem(suggestion.name)} > {suggestion.name} {suggestion.reason} )} ListEmptyComponent={No suggestions available} /> )} setShowAIModal(false)}> Close ); } /** * Item row component */ function ItemRow({ listItem, item, onCheck, onLongPress, }: { listItem: ListItem; item?: Item; onCheck: () => void; onLongPress: () => void; }) { return ( {listItem.checked && ✓} {item?.name || 'Unknown item'} {listItem.quantity > 1 && Qty: {listItem.quantity}} ); } /** * Sort option component */ function SortOption({ label, value, current, onPress, }: { label: string; value: SortOption; current: SortOption; onPress: (value: SortOption) => void; }) { return ( { onPress(value); }} > {value === current ? '● ' : '○ '} {label} ); } 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', }, });