import { useState } from 'react'
import { FormEventHandler } from 'react'
import useAllChat from '../../hooks/useAllChat'
import './Chat.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPaperPlane } from '@fortawesome/free-regular-svg-icons'
import { getColorForUserName } from '../../background/style/colorednames'
interface Props {
    sendMessage: Function
}

function Chat({ sendMessage }: Props) {
    const [chatInput, setChatInput] = useState('')
    const { chatMesages } = useAllChat()

    const onInput: React.ChangeEventHandler<HTMLInputElement> = (event) => {
        setChatInput(event.target.value)
        event.preventDefault()
    }

    const onSubmit: FormEventHandler<HTMLFormElement> = (event) => {
        event.preventDefault()
        sendMessage(JSON.stringify({ content: chatInput }))
        setChatInput('')
    }

    return (
        <div className="chat">
            <div className="chat-messages">
                {chatMesages
                    .slice()
                    .reverse() // reverse because of css, don't aks me
                    .map((message) => {
                        const nameStyle = {
                            color: getColorForUserName(message.sender.name),
                        }
                        return (
                            <div className="chat-bubble" key={message.uuid}>
                                {' '}
                                <span className="chat-sender" style={nameStyle}>
                                    {message.sender.name} <br />{' '}
                                </span>{' '}
                                {message.content}{' '}
                            </div>
                        )
                    })}
            </div>
            <form className="chat-input-form" onSubmit={onSubmit}>
                <input
                    className="chat-input"
                    placeholder="Say something funny :D"
                    type="text"
                    value={chatInput}
                    onChange={onInput}
                />
                <button type="submit">
                    <FontAwesomeIcon icon={faPaperPlane} />
                </button>
            </form>
        </div>
    )
}

export default Chat
