import React, { useState, useRef, useEffect } from 'react';
import { Container, Row, Col, Button } from 'reactstrap';
import { useDispatch, useSelector } from 'react-redux';
import { fetchLobbyChatMessages, postNewChatMessage } from '../../store/features/lobbyChatMessagesSlice';
import { useAuth } from '../../context/UserAuth';
import JKProfileAvatar from '../profile/JKProfileAvatar';
import TimeAgo from '../common/JKTimeAgo';
import { Scrollbar } from 'react-scrollbars-custom';

function JKLobbyChat() {
  const CHANNEL_LOBBY = 'lobby';
  const LIMIT = 10;
  const [newMessage, setNewMessage] = useState('');
  const dispatch = useDispatch();
  const messageTextBox = useRef();
  const scrollbar = useRef();
  const scrolledToBottom = useRef(false);
  const { currentUser } = useAuth();
  const [fetching, setFetching] = useState(false);
  const [messagesArrived, setMessagesArrived] = useState(false);
  const [offset, setOffset] = useState(0);

  const chatMessages = useSelector(state => state.lobbyChat.messages);
  const createStatus = useSelector(state => state.lobbyChat.create_status);

  const fetchMessages = async () => {
    const options = { offset: offset, limit: LIMIT };
    try {
      setFetching(true);
      await dispatch(fetchLobbyChatMessages(options)).unwrap();
      if(chatMessages.length < LIMIT){
        goToBottom();
      }
    } catch (err) {
      console.log('ERROR', err);
    } finally {
      setFetching(false);
    }
  };

  useEffect(() => {
    fetchMessages();
  }, []);

  useEffect(() => {
    if (scrollbar && scrollbar.current) {
      if (!fetching && !scrollAtTop()) {
        if (chatMessages[chatMessages.length - 1]['user_id'] !== currentUser.id) {
          if (!scrolledToBottom.current) {
            setMessagesArrived(true);
          } else {
            goToBottom();
          }
        } else {
          goToBottom();
        }
      }
    }
  }, [chatMessages]);

  useEffect(() => {
    if (!messagesArrived) {
      
      goToBottom();
    }
  }, [messagesArrived]);

  useEffect(() => {
    if (offset !== 0) {
      fetchMessages();
    }
  }, [offset]);

  const handleOnKeyPress = event => {
    if (event.key === 'Enter' || event.key === 'NumpadEnter') {
      event.preventDefault();
      sendMessage();
      event.target.value = '';
    }
  };

  const sendMessage = () => {
    let msgData = {
      message: newMessage,
      channel: CHANNEL_LOBBY,
      user_id: currentUser.id
    };
    setNewMessage('');

    try {
      dispatch(postNewChatMessage(msgData));
    } catch (err) {
      console.log('addNewMessage error', err);
    }
  };

  useEffect(() => {
    if (createStatus === 'succeeded') {
      fetchMessages();
      messageTextBox.current.focus();
    }
  }, [createStatus]);

  const scrollAtTop = () => {
    return scrollbar.current.scrollTop === 0;
  };

  const goToBottom = () => {
    if (scrollbar && scrollbar.current) {
      scrollbar.current.scrollToBottom();
    }
  };

  const handleScrollStop = scrollValues => {
    console.log('handleScrollStop', scrollValues);
    scrolledToBottom.current = false;
    if (scrollValues.scrollTop === 0) {
      setOffset(prev => prev + 1);
    } else if (scrollValues.scrollTop === scrollValues.scrollHeight - scrollValues.clientHeight) {
      scrolledToBottom.current = true;
      setMessagesArrived(false);
    }
  };

  const containerStyle = {
    display: 'flex',
    flexDirection: 'column',
    height: '200'
  };

  return (
    <div>
      <div className="bg-200 text-900" style={{ padding: '0.75rem' }}>
        Lobby Chat
      </div>
      <div className="border pt-1 pl-3 p-2" style={containerStyle}>
        <div style={{ height: '400px' }}>
          <Scrollbar
            ref={scrollbar}
            onScrollStop={handleScrollStop}
            style={{ width: '100%', height: 400 }}
            mobileNative={true}
            trackClickBehavior="step"
          >
            {chatMessages.map(message => (
              <div className="d-flex mb-3 mr-1 text-message-row" key={message.id}>
                <div className="avatar avatar-2xl d-inline-block">
                  <JKProfileAvatar url={message.user.photo_url} />
                </div>
                <div className="d-inline-block">
                  <div className="d-flex flex-column">
                    <div>
                      <strong>{message.user.name}</strong>
                      <time className="notification-time ml-2 t-1">
                        <TimeAgo date={message.created_at} />
                      </time>
                    </div>
                    <div>{message.message}</div>
                  </div>
                </div>
              </div>
            ))}
          </Scrollbar>
          {messagesArrived && (
            <div className="d-flex justify-content-center">
              <Button color="info" size="sm" onClick={() => setMessagesArrived(prev => !prev)}>
                New messages
              </Button>
            </div>
          )}
        </div>
        <div className="mt-2" style={{ height: '20%' }}>
          <textarea
            style={{ width: '100%' }}
            value={newMessage}
            onChange={e => setNewMessage(e.target.value)}
            onKeyPress={handleOnKeyPress}
            ref={messageTextBox}
          />
        </div>
        <div className="d-flex justify-content-end" style={{ height: '10%' }}>
          <Button color="primary" onClick={sendMessage} disabled={!newMessage}>
            Send Message
          </Button>
        </div>
      </div>
    </div>
  );
}

export default JKLobbyChat;
