import React, { useState, useEffect } from 'react';
import { View } from 'react-native';
import { Conversation, Message } from '@/app/lib/conversation';
import MessageBubble from '@/components/ui/MessageBubble';
import { NavigationProp, ParamListBase } from '@react-navigation/native';
import { language_matrix_entry, Translator } from '@/app/i18n/api';
import { getDb } from '@/app/lib/db';

interface ConversationThreadProps {
  conversation: Conversation;
}

const ConversationThread = ({ language, navigation }: { language: language_matrix_entry, navigation: NavigationProp<ParamListBase> }) => {
  const [messages, setMessages] = useState<Message[]>([]);

  useEffect(async () => {
    const db = await getDb();
    const curs = await db.executeSql("SELECT host_language FROM settings LIMIT 1");
  })

  const translator = new Translator()

  const conversation = new Conversation()

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

    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;