import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import io from 'socket.io-client'
import { useTailwind } from 'tailwind-rn';

function ConversationScreen({ route, navigation }) {
  const { otherUserId } = route.params;
  const [directMessages, setDirectMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [newMessage, setNewMessage] = useState('');
    const tailwind = useTailwind();

  async function fetchDirectMessages() {
    setIsLoading(true);
    try {
      const token = await AsyncStorage.getItem('token');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const response = await fetch(`${apiUrl}/api/v1/app/dms/${otherUserId}`, {
        headers: { 'Authorization': token },
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch direct messages: ${response.status}`);
      }

      const messages = await response.json();
      setDirectMessages(messages);
    } catch (error) {
      console.error('Error:', error);
      setErrorMessage(error.message);
    } finally {
      setIsLoading(false);
    }
  }

  async function handleSendMessage() {
    const token = await AsyncStorage.getItem('token');
    const senderId = await AsyncStorage.getItem('userID');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')
    const response = await fetch(`${apiUrl}/api/v1/app/dms/send`, {
      method: 'POST',
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ recipientId: otherUserId, text: newMessage, senderId: senderId }),
    });

    if (!response.ok) {
      throw new Error(`Failed to send message: ${response.status}`);
    }

    const message = await response.json();
    setNewMessage('');
  }

  useEffect(() => {
    async function setupSocket() {
      const senderId = await AsyncStorage.getItem('userID');
      console.log('Sender ID:', senderId);
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const socket = io(apiUrl);
      socket.emit('user connected', senderId);
      socket.on('new_dm', (newDm) => {
        setDirectMessages(prevMessages => [...prevMessages, newDm]);
    });
    }
  
    async function setup() {
      await fetchDirectMessages();
      await setupSocket();
    }
  
    setup();
  }, []);
  


  return (
    <View style={tailwind('flex-auto')}>
      {/* Display a loading indicator while the messages are being fetched */}
      {isLoading && <ActivityIndicator size="large" color="#0000ff" />}
      {errorMessage !== '' && <Text>{errorMessage}</Text>}

      {/* Render the list of direct messages */}
      <View style={tailwind('flex-1')}>
  <FlatList
    style={tailwind('flex-1')}
    contentContainerStyle={tailwind('pb-12')}
    data={directMessages}
    keyExtractor={(item) => item._id}
    renderItem={({ item }) => (
      <Text>
        {item.sender.username}: {item.content}
      </Text>
    )}
  />
        </View>

      {/* Render the text input and send button */}
      <View style={tailwind('flex-row items-center mb-3')}> 
        <TextInput
          style={tailwind('flex-1 border border-gray-500 mr-3 px-2')} 
          value={newMessage}
          onChangeText={setNewMessage}
          placeholder="Type a message"
        />
        <Button title="Send" onPress={handleSendMessage} />
      </View> 
    </View>
);
}


export default ConversationScreen;
