import React, { useState, useEffect } from 'react';
import { View, Text, Button, FlatList, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

function DirectMessagesScreen({ navigation }) {
  const [conversations, setConversations] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    const fetchConversations = async () => {
      const userId = await AsyncStorage.getItem('userID');
      const token = await AsyncStorage.getItem('token');
            const apiUrl = await AsyncStorage.getItem('apiEndpoint')

      const response = await fetch(`http://192.168.1.107:1989/api/v1/app/dms/`, {
        headers: { 'Authorization': token },
      });
  
      if (response.ok) {
        const data = await response.json();
        setConversations(data);
      } else {
        console.error(`Failed to fetch conversations: ${response.status}`);
      }
    };
  
    fetchConversations();
    console.warn(conversations)
  }, []);
  

  return (
    <FlatList
  data={conversations}
  keyExtractor={(item) => item.userId}
  renderItem={({ item }) => (
    <Text onPress={() => navigation.navigate('Conversation', { otherUserId: item.userId }, console.warn("item", item))}>
      {item.username}: {item.messages[0].content}
    </Text>
  )}
/>

  );
}

export default DirectMessagesScreen;
