import { useState, useEffect } from 'react'; import { XStack, Paragraph, YStack, Button, H6, Avatar, Text } from 'tamagui'; import { useRouter } from 'expo-router'; export default function MessagesPage() { const [friends, setFriends] = useState([]); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(true); const router = useRouter(); const navigateToChat = (contact) => { router.push({ pathname: `/chat/${contact.username}`, // Use dynamic route params: { friendUsername: contact.username }, // Pass necessary params }); }; useEffect(() => { const fetchFriends = async () => { try { const authToken = localStorage.getItem('jwtToken'); // Retrieve JWT token if (!authToken) { console.error('User is not authenticated'); return; } const response = await fetch('http://localhost:4000/friends', { headers: { 'Authorization': `Bearer ${authToken}`, }, }); if (!response.ok) { throw new Error('Failed to fetch friends'); } const data = await response.json(); setFriends(data); // Set friends list } catch (err) { console.error('Error fetching friends:', err); } finally { setLoading(false); } }; fetchFriends(); }, []); useEffect(() => { // Fetch messages for each friend const fetchMessages = async () => { const authToken = localStorage.getItem('jwtToken'); // Retrieve JWT token if (!authToken) { console.error('User is not authenticated'); return; } try { const newMessages = []; // Fetch the latest message for each friend for (let friend of friends) { console.log(friend) const response = await fetch(`http://localhost:4000/messages?receiverUsername=${friend.username}`, { headers: { 'Authorization': `Bearer ${authToken}`, }, }); if (response.ok) { const messagesData = await response.json(); if (messagesData.length > 0) { const latestMessage = messagesData[messagesData.length - 1]; // Get the most recent message newMessages.push({ username: friend.username, lastMessage: latestMessage.content, timestamp: latestMessage.createdAt, avatarUrl: friend.avatarUrl || 'https://i.pravatar.cc/150?img=1', // Default avatar if not available }); } } } setMessages(newMessages); } catch (err) { console.error('Error fetching messages:', err); } finally { setLoading(false); } }; if (friends.length > 0) { fetchMessages(); } else { setLoading(false); // If no friends, stop loading } }, [friends]); if (loading) { return Loading...; } return (
People You've Messaged
{/* Check if there are no friends */} {friends.length === 0 ? ( You have no friends yet. Add some friends to start chatting! ) : ( // Check if there are no messages messages.length === 0 ? ( No messages yet. Start a conversation! ) : ( messages.map((message, index) => ( {/* Profile Picture */} {/* Username */} {message.username} {/* Last message preview */} {message.lastMessage} {/* Timestamp */} {new Date(message.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} {/* Button to open chat */} )) ) )}
); }