import { useState } from 'react'; import { View, Text, TextInput, Pressable, StyleSheet, ScrollView, ActivityIndicator, FlatList, Modal, Platform, } from 'react-native'; import { useRouter, useLocalSearchParams } from 'expo-router'; import { useListsStore } from '@/store/lists'; import { useItemsStore } from '@/store/items'; import { useWebSocketActions } from '@/hooks/useWebSocket'; import { api } from '@/lib/api'; import type { Item, ListItem } from '@shop/types'; /** * Add item sheet screen * Allows users to: search items, scan barcode, or manually add item */ export default function AddItemScreen() { const router = useRouter(); const { id } = useLocalSearchParams<{ id: string }>(); const { lists, updateList } = useListsStore(); const { items, setItems } = useItemsStore(); const { notifyItemAdded } = useWebSocketActions(); const [tab, setTab] = useState<'search' | 'barcode' | 'manual'>('search'); const [searchQuery, setSearchQuery] = useState(''); const [searchResults, setSearchResults] = useState([]); const [isSearching, setIsSearching] = useState(false); const [barcode, setBarcode] = useState(''); const [manualName, setManualName] = useState(''); const [manualQuantity, setManualQuantity] = useState('1'); const [selectedAisleId, setSelectedAisleId] = useState(); const [isAdding, setIsAdding] = useState(false); const list = lists.find((l) => l.id === id); const handleSearch = async (query: string) => { setSearchQuery(query); if (query.trim().length < 2) { setSearchResults([]); return; } try { setIsSearching(true); const results = await api.get(`/api/items/search?q=${encodeURIComponent(query)}`); setSearchResults(results); } catch (err) { console.error('Search failed:', err); } finally { setIsSearching(false); } }; const handleBarcodeSearch = async () => { if (!barcode.trim()) return; try { setIsSearching(true); const item = await api.get(`/api/items/barcode/${barcode}`); if (item) { setSearchResults([item]); } else { // Barcode not found, allow manual entry setSearchResults([]); setManualName(''); } } catch (err) { console.error('Barcode search failed:', err); } finally { setIsSearching(false); } }; const handleAddItem = async (itemId?: string) => { if (!list || !id) return; try { setIsAdding(true); let finalItemId = itemId; // If no itemId provided, create a new item first if (!finalItemId) { const newItem = await api.post('/api/items', { name: manualName, aisleId: selectedAisleId, }); finalItemId = newItem.id; } // Add item to list const newListItem: ListItem = { id: `li-${Date.now()}`, // Temporary ID itemId: finalItemId, quantity: parseInt(manualQuantity, 10) || 1, checked: false, addedBy: 'current-user', // TODO: Get from auth store excludedFromPreset: false, }; await api.post(`/api/lists/${id}/items`, { itemId: finalItemId, quantity: newListItem.quantity, }); // Notify other devices via WebSocket notifyItemAdded(id, newListItem); // Update local store const updatedList = { ...list, items: [...list.items, newListItem], }; updateList(updatedList); // Go back to list router.back(); } catch (err) { console.error('Failed to add item:', err); } finally { setIsAdding(false); } }; if (!list) { return ( List not found ); } return ( {/* Header */} router.back()}> ✕ Add Item {/* Tab buttons */} setTab('search')} /> setTab('barcode')} /> setTab('manual')} /> {/* Tab content */} {/* Search Tab */} {tab === 'search' && ( {isSearching ? ( ) : ( item.id} scrollEnabled={false} renderItem={({ item }) => ( { setManualQuantity('1'); handleAddItem(item.id); }} > {item.name} {item.aisleId && ( Aisle: {item.aisleId} )} + )} ListEmptyComponent={ searchQuery.trim().length >= 2 ? ( No items found ) : ( Type to search ) } /> )} )} {/* Barcode Tab */} {tab === 'barcode' && ( router.push(`/(app)/list/${id}/barcode-scan`)} > 🎥 Scan Barcode OR {isSearching ? ( ) : ( Search Barcode )} {searchResults.length > 0 && ( item.id} scrollEnabled={false} renderItem={({ item }) => ( { setManualQuantity('1'); handleAddItem(item.id); }} > {item.name} {item.barcode && ( Barcode: {item.barcode} )} + )} /> )} )} {/* Manual Tab */} {tab === 'manual' && ( Item Name Quantity setManualQuantity(Math.max(1, parseInt(manualQuantity, 10) - 1).toString()) } > − setManualQuantity((parseInt(manualQuantity, 10) + 1).toString())} > + handleAddItem()} disabled={!manualName.trim() || isAdding} > {isAdding ? ( ) : ( Add Item )} )} ); } /** * Tab button component */ function TabButton({ label, active, onPress, }: { label: string; active: boolean; onPress: () => void; }) { return ( {label} ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 12, marginTop: Platform.OS === 'ios' ? 44 : 12, borderBottomWidth: 1, borderBottomColor: '#e0e0e0', }, title: { fontSize: 18, fontWeight: '600', color: '#000', }, closeButton: { fontSize: 20, color: '#007AFF', }, tabContainer: { flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#e0e0e0', }, tabButton: { flex: 1, paddingVertical: 12, alignItems: 'center', borderBottomWidth: 2, borderBottomColor: 'transparent', }, tabButtonActive: { borderBottomColor: '#007AFF', }, tabButtonText: { fontSize: 14, fontWeight: '500', color: '#666', }, tabButtonTextActive: { color: '#007AFF', }, content: { flex: 1, padding: 16, }, centerContainer: { justifyContent: 'center', alignItems: 'center', paddingVertical: 32, }, input: { borderWidth: 1, borderColor: '#ddd', borderRadius: 8, paddingHorizontal: 12, paddingVertical: 10, fontSize: 16, marginBottom: 16, backgroundColor: '#f9f9f9', }, label: { fontSize: 14, fontWeight: '600', color: '#000', marginBottom: 8, }, scanButton: { backgroundColor: '#007AFF', paddingVertical: 12, borderRadius: 8, justifyContent: 'center', alignItems: 'center', marginBottom: 16, }, scanButtonText: { color: '#fff', fontSize: 16, fontWeight: '600', }, quantityContainer: { flexDirection: 'row', alignItems: 'center', marginBottom: 16, gap: 12, }, quantityButton: { width: 40, height: 40, borderRadius: 8, backgroundColor: '#f0f0f0', justifyContent: 'center', alignItems: 'center', }, quantityButtonText: { fontSize: 20, color: '#007AFF', fontWeight: '600', }, quantityInput: { flex: 1, borderWidth: 1, borderColor: '#ddd', borderRadius: 8, paddingHorizontal: 12, fontSize: 16, textAlign: 'center', }, resultItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingVertical: 12, paddingHorizontal: 12, marginVertical: 4, backgroundColor: '#f9f9f9', borderRadius: 8, borderLeftWidth: 4, borderLeftColor: '#007AFF', }, resultInfo: { flex: 1, }, resultName: { fontSize: 16, fontWeight: '500', color: '#000', }, resultAisle: { fontSize: 12, color: '#666', marginTop: 4, }, addButton: { fontSize: 20, color: '#007AFF', fontWeight: '600', marginLeft: 12, }, emptyText: { textAlign: 'center', color: '#999', fontSize: 14, marginVertical: 24, }, divider: { flexDirection: 'row', alignItems: 'center', marginVertical: 16, }, dividerLine: { flex: 1, height: 1, backgroundColor: '#ddd', }, dividerText: { marginHorizontal: 12, fontSize: 12, fontWeight: '600', color: '#999', }, addButtonText: { color: '#fff', fontSize: 16, fontWeight: '600', }, });