import React, { useState, useEffect } from 'react'; import { View, Text, Image, TextInput, TouchableOpacity, FlatList, SafeAreaView, ActivityIndicator } from 'react-native'; import { Feather, FontAwesome, Ionicons } from '@expo/vector-icons'; import { router } from 'expo-router'; import { useAuth } from '../../context/auth-context'; import { getFoods } from '../../services/data/foods'; import { getLikesCount, getSavesCount, getCommentsCount } from '../../services/data/forum'; import { Food } from '../../types/index'; // Categories for filtering const categories = [ { id: 'main', name: 'Main dish' }, { id: 'dessert', name: 'Dessert' }, { id: 'appetizer', name: 'Appetite' }, ]; // Sort options const sortOptions = [ { id: 'rating', name: 'Rating', icon: 'star' }, { id: 'newest', name: 'Newest', icon: 'calendar' }, { id: 'best', name: 'Best', icon: 'fire' }, ]; export default function ForumScreen() { const { isAuthenticated } = useAuth(); const [searchQuery, setSearchQuery] = useState(''); const [foods, setFoods] = useState([]); const [loading, setLoading] = useState(true); const [selectedCategory, setSelectedCategory] = useState(''); const [selectedSort, setSelectedSort] = useState('rating'); const [foodStats, setFoodStats] = useState<{[key: string]: {likes: number, saves: number, comments: number}}>({}); useEffect(() => { loadFoods(); }, [selectedCategory, selectedSort]); const loadFoods = async () => { setLoading(true); try { // In a real app, you would filter by category and sort accordingly const { data, error } = await getFoods(undefined, true, searchQuery); if (error) { console.error('Error loading foods:', error); return; } if (data) { // Sort data based on selectedSort let sortedData = [...data]; if (selectedSort === 'rating') { // Assuming higher calories means higher rating for demo purposes sortedData.sort((a, b) => (b.calories ?? 0) - (a.calories ?? 0)); } else if (selectedSort === 'newest') { sortedData.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); } else if (selectedSort === 'best') { // Assuming higher ingredient_count means better for demo purposes sortedData.sort((a, b) => (b.ingredient_count ?? 0) - (a.ingredient_count ?? 0)); } setFoods(sortedData.map(food => ({ ...food, description: food.description || '', // Ensure description is always a string ingredient_count: food.ingredient_count ?? 0, // Ensure ingredient_count is always a number calories: food.calories ?? 0, // Ensure calories is always a number image_url: food.image_url || '', // Ensure image_url is always a string }))); // Load stats for each food const statsPromises = sortedData.map(async (food) => { const [likesRes, savesRes, commentsRes] = await Promise.all([ getLikesCount(food.id), getSavesCount(food.id), getCommentsCount(food.id) ]); return { foodId: food.id, likes: likesRes.count || 0, saves: savesRes.count || 0, comments: commentsRes.count || 0 }; }); const stats = await Promise.all(statsPromises); const statsMap = stats.reduce((acc, stat) => { acc[stat.foodId] = { likes: stat.likes, saves: stat.saves, comments: stat.comments }; return acc; }, {} as {[key: string]: {likes: number, saves: number, comments: number}}); setFoodStats(statsMap); } } catch (error) { console.error('Error:', error); } finally { setLoading(false); } }; const handleSearch = (text: string) => { setSearchQuery(text); // Debounce search for better performance setTimeout(() => { loadFoods(); }, 500); }; const navigateToPostDetail = (food: Food) => { router.push({ pathname: '/post-detail', params: { id: food.id } }); }; const renderFoodItem = ({ item }: { item: Food }) => { // Get stats for this food const stats = foodStats[item.id] || { likes: 0, saves: 0, comments: 0 }; // Mock data for UI elements not in the Food type const username = 'Mr. Chef'; const rating = 4.2; return ( navigateToPostDetail(item)} > {/* User info and rating */} {username} {rating} {/* Food image */} {/* Food title and description */} {item.name} {item.description} {/* Interaction buttons */} {stats.comments} {stats.comments} {stats.likes} ); }; return ( {/* Search Bar */} {/* Categories */} item.id} renderItem={({ item }) => ( setSelectedCategory(item.id === selectedCategory ? '' : item.id)} > {item.name} )} /> {/* Sort Options */} item.id} renderItem={({ item }) => ( setSelectedSort(item.id)} > {item.name} )} /> {/* Food Posts */} {loading ? ( ) : ( item.id} renderItem={renderFoodItem} contentContainerStyle={{ padding: 16 }} showsVerticalScrollIndicator={false} /> )} ); }