import { useState, useEffect } from 'react';
import { XStack, Paragraph, YStack, Button, Text, H6, Avatar } from 'tamagui';
import { useRouter } from 'expo-router';

export default function ContactsPage() {
  const [contacts, setContacts] = useState([]);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  // Fetch friends from the server
  const fetchFriends = async () => {
    try {
      const authToken = localStorage.getItem('jwtToken'); // Retrieve JWT token
      if (!authToken) {
        throw new Error('Authentication required. Please log in.');
      }

      const response = await fetch('http://localhost:4000/friends', {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || 'Failed to fetch contacts');
      }

      const friends = await response.json();
      setContacts(friends);
    } catch (err) {
      console.error('Error fetching friends:', err);
      setError(err.message || 'Failed to load contacts.');
    } finally {
      setLoading(false);
    }
  };

  // Navigate to chat screen
  const navigateToChat = (contact) => {
    router.push({
      pathname: `/chat/${contact.username}`, // Use dynamic route
      params: { friendUsername: contact.username }, // Pass necessary params
    });
  };

  useEffect(() => {
    fetchFriends();
  }, []);

  return (
    <YStack flex={1} bg="$background" px="$5" pt="$5">
      <H6 fontSize={25} mb="$4" color="$primaryText">
        Your Contacts
      </H6>

      {loading ? (
        <Text>Loading contacts...</Text>
      ) : error ? (
        <Text color="red">{error}</Text>
      ) : contacts.length === 0 ? (
        <Text>No contacts found. Add some friends to start chatting!</Text>
      ) : (
        contacts.map((contact) => (
          <XStack
            key={contact.id}
            bg="$backgroundLight"
            padding="$4"
            borderRadius="$12"
            mb="$3"
            space="$3"
            alignItems="center"
            hoverStyle={{ bg: '$gray8' }}
          >
            {/* Profile Picture */}
            <Avatar size={50} circular>
              <Avatar.Image
                src={`/assets/images/Gnome_child.png`} // Placeholder avatar
                alt={`${contact.username}'s avatar`}
              />
            </Avatar>

            {/* Contact Details */}
            <YStack flex={1} alignItems="flex-start">
              <Paragraph fontSize={18} fontWeight="bold" color="$primaryText">
                {contact.username}
              </Paragraph>
              <Text fontSize={14} color="$secondaryText">
                {contact.status} {/* Placeholder for online/offline */}
              </Text>
            </YStack>

            {/* Message Button */}
            <Button
              size="$2"
              onPress={() => navigateToChat(contact)}
              theme="blue"
            >
              Message
            </Button>
          </XStack>
        ))
      )}
    </YStack>
  );
}
