import React from 'react';
import { useRealtimeKitSelector } from '../../src';

function Chat() {
    const roomJoined = useRealtimeKitSelector(
        (meeting) => meeting.self.roomJoined,
    );
    const chat = useRealtimeKitSelector((meeting) => meeting.chat);
    if (!roomJoined) {
        return null;
    }

    return (
        <fieldset className="section">
            <legend>Chat</legend>
            <div>
                <ul>
                    {chat?.messages.map(
                        (message: any) => (
                            <li key={message.id}>
                                {message.type}
                                -
                                {message.type === 'text' && message.message}
                            </li>
                        ),
                    )}
                </ul>
                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        const messageInput = (e.target as any).elements
                            .message as HTMLInputElement;
                        const message = messageInput.value.trim();

                        if (message !== '') {
                            if (chat) {
                                chat.sendTextMessage(message);
                            }
                            messageInput.value = '';
                        }
                    }}
                >
                    <input type="text" name="message" />
                    <button type="submit">Send</button>
                </form>
            </div>
        </fieldset>
    );
}

export default Chat;
