import React, { useState, useEffect } from 'react';
import { View } from 'react-native';
import { Conversation } from '@/app/lib/conversation';
import MessageBubble from '@/components/ui/MessageBubble';

interface ConversationThreadProps {
  conversation: Conversation;
}

const ConversationThread: React.FC<ConversationThreadProps> = ({ conversation }) => {
  const [messages, setMessages] = useState<Message[]>(conversation.messages);

  useEffect(() => {
    const updateMessages = () => {
      setMessages([...conversation.messages]);
    };

    conversation.on('messageAdded', updateMessages);
    conversation.on('messageUpdated', updateMessages);

    return () => {
      conversation.off('messageAdded', updateMessages);
      conversation.off('messageUpdated', updateMessages);
    };
  }, [conversation]);

  const renderMessages = () => (
    messages.map((message, index) => (
      <MessageBubble key={index} message={message} />
    ))
  );

  return (
    <View style={{ flex: 1 }}>
      {renderMessages()}
    </View>
  );
};

export default ConversationThread;