import { FC, useRef, useEffect, useState } from 'react'
import TopInfo from './TopInfo';
import Message from './Message';
import EmptyChat from './EmptyChat';
import SendMessage from './SendMessage';
import { useAppSelector } from '../../../hooks/redux';
import MessageMenu from './MessageMenu/MessageMenu';
import { IContext } from '../../../models/IContext';

const Chat: FC = () => {
    const [context, setContext] = useState<IContext>({
        active: false,
        x: 0,
        y: 0,
        message_id: ''
    });
    const messagesEndRef = useRef<HTMLDivElement>(null)
    const { user } = useAppSelector(state => state.UserSlice)
    const { chat } = useAppSelector(state => state.MessengerSlice)
    useEffect(() => {
        if(messagesEndRef.current) {
            messagesEndRef.current.scrollIntoView()
        }
    }, [chat.messages])

    return (
        <div className='w-full bg-gray-300 bg-chat-pattern flex flex-col'>
            <TopInfo data={chat.user}/>
            <div className={['flex-grow custom-scroll', context.active ? 'overflow-y-hidden' : 'overflow-y-auto'].join(' ')}>
                <div className={['w-full flex flex-col mx-auto max-w-[1200px]', chat.messages.length > 0 ? 'mt-10' : 'h-full justify-center'].join(' ')}>
                    {chat.messages.length > 0
                    ?
                    <>
                    {chat.messages.map(message=>
                        <Message key={message._id} msg={message} user={message.from === user._id ? user : chat.user} isMe={message.from === user._id ? true : false} setContext={setContext}/>
                    )}
                    <MessageMenu context={context} setContext={setContext}/>
                    <div ref={messagesEndRef}></div>
                    </>
                    :
                    <EmptyChat/>
                    }
                    
                </div>
            </div>
            <SendMessage/>
        </div>
    )
}

export default Chat;