import React, { useState, useEffect } from 'react'; import { View, Text, Image, TouchableOpacity, ScrollView, SafeAreaView, ActivityIndicator, TextInput, KeyboardAvoidingView, Platform } from 'react-native'; import { Feather, FontAwesome } from '@expo/vector-icons'; import { useLocalSearchParams, router } from 'expo-router'; import { useAuth } from '../context/auth-context'; import { getFoods, getIngredients, getNutrients } from '../services/data/foods'; import { createLike, deleteLike, createSave, deleteSave, getComments, createComment, getLikesCount, getSavesCount, getCommentsCount, checkUserLiked, checkUserSaved } from '../services/data/forum'; import { Food, Ingredient, Nutrient, FoodComment } from '../types/index'; export default function PostDetailScreen() { const { id } = useLocalSearchParams(); const authContext = useAuth(); const { isAuthenticated } = authContext || {}; // Adjust based on the actual structure of AuthContextType const [food, setFood] = useState(null); const [ingredients, setIngredients] = useState([]); const [nutrients, setNutrients] = useState(null); const [comments, setComments] = useState([]); const [loading, setLoading] = useState(true); const [isLiked, setIsLiked] = useState(false); const [isSaved, setIsSaved] = useState(false); const [showReviews, setShowReviews] = useState(true); const [commentText, setCommentText] = useState(''); const [submittingComment, setSubmittingComment] = useState(false); const [stats, setStats] = useState({ likes: 0, saves: 0, comments: 0 }); // Mock data for UI elements const username = 'Mr. Chef'; const rating = 4.2; useEffect(() => { if (id) { loadFoodDetails(); } }, [id]); const loadFoodDetails = async () => { setLoading(true); try { // Get food details const { data: foodData, error: foodError } = await getFoods(undefined, undefined, undefined, 1, 0); if (foodError) { console.error('Error loading food:', foodError); return; } if (foodData && foodData.length > 0) { setFood({ ...foodData[0], description: foodData[0].description || '', // Ensure description is always a string ingredient_count: foodData[0].ingredient_count ?? 0, // Provide default value for ingredient_count calories: foodData[0].calories ?? 0, // Provide default value for calories image_url: foodData[0].image_url || '', // Provide default value for image_url }); // Get ingredients const { data: ingredientsData, error: ingredientsError } = await getIngredients(foodData[0].id); if (!ingredientsError && ingredientsData) { setIngredients(ingredientsData); } // Get nutrients const { data: nutrientsData, error: nutrientsError } = await getNutrients(foodData[0].id); if (!nutrientsError && nutrientsData) { setNutrients(nutrientsData); } // Get comments const { data: commentsData, error: commentsError } = await getComments(foodData[0].id); if (!commentsError && commentsData) { setComments(commentsData); } // Get stats const [likesRes, savesRes, commentsRes] = await Promise.all([ getLikesCount(foodData[0].id), getSavesCount(foodData[0].id), getCommentsCount(foodData[0].id) ]); setStats({ likes: likesRes.count || 0, saves: savesRes.count || 0, comments: commentsRes.count || 0 }); // Check if user has liked/saved if (isAuthenticated) { const userId = 'current-user-id'; // Replace with actual user ID const [likedRes, savedRes] = await Promise.all([ checkUserLiked(foodData[0].id, userId), checkUserSaved(foodData[0].id, userId) ]); setIsLiked(!!likedRes.data); setIsSaved(!!savedRes.data); } } } catch (error) { console.error('Error:', error); } finally { setLoading(false); } }; const handleLike = async () => { if (!authContext.isAuthenticated || !food) return; try { const userId = 'current-user-id'; // Replace with actual user ID if (isLiked) { await deleteLike(food.id, userId); setIsLiked(false); setStats(prev => ({ ...prev, likes: Math.max(0, prev.likes - 1) })); } else { await createLike(food.id, userId); setIsLiked(true); setStats(prev => ({ ...prev, likes: prev.likes + 1 })); } } catch (error) { console.error('Error toggling like:', error); } }; const handleSave = async () => { if (!authContext.isAuthenticated || !food) return; try { const userId = 'current-user-id'; // Replace with actual user ID if (isSaved) { await deleteSave(food.id, userId); setIsSaved(false); setStats(prev => ({ ...prev, saves: Math.max(0, prev.saves - 1) })); } else { await createSave(food.id, userId); setIsSaved(true); setStats(prev => ({ ...prev, saves: prev.saves + 1 })); } } catch (error) { console.error('Error toggling save:', error); } }; const handleSubmitComment = async () => { if (!authContext.isAuthenticated || !food || !commentText.trim()) return; setSubmittingComment(true); try { const userId = 'current-user-id'; // Replace with actual user ID await createComment(food.id, userId, commentText.trim()); // Refresh comments const { data: commentsData } = await getComments(food.id); if (commentsData) { setComments(commentsData); setStats(prev => ({ ...prev, comments: prev.comments + 1 })); } setCommentText(''); } catch (error) { console.error('Error submitting comment:', error); } finally { setSubmittingComment(false); } }; if (loading) { return ( ); } if (!food) { return ( Post not found router.back()} > Go Back ); } return ( {/* Header */} router.back()} > Post {/* User info and rating */} {username} {rating} {/* Food image */} {/* Food title and description */} {food.name} {food.description} 09:41 - 4/3/25 {/* Interaction buttons */} {stats.comments} {stats.comments} {stats.likes} {/* Reviews section */} setShowReviews(!showReviews)} > Review {showReviews && ( {comments.length > 0 ? ( comments.map((comment) => ( {comment.user_id} {new Date(comment.created_at).toLocaleDateString()} {comment.content} )) ) : ( No reviews yet. Be the first to comment! )} )} {/* Bottom spacing */} {/* Comment input */} ); }