import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { chatActions } from '../store/chat-slice';

const TypingBar = ({id}) => {
    const [rerender, setRerender] = useState(false)

    const dispatch = useDispatch();
    const {typings} = useSelector(s => s.chat)
    
    // On componentDidMount set the timer
    useEffect(() => {
      const timeout = setTimeout(() => {
        dispatch(chatActions.removeTyping());
        setRerender(!rerender)
        
        return () => clearTimeout(timeout)
      }, 2500)
    }, [rerender, dispatch]);

  return (
    <div className='text-dark'>
        {typings.filter(n => n.roomId === id).length > 1 ? <p className='p-0 m-0 text-start w-100 text-muted pt-1'>2 or more users are typing</p> : typings.map(n=> n.roomId === id ? <p key={n.message} className='p-0 m-0 text-start w-100 text-muted pt-1'>{n.message}</p> : '')}    
    </div>
  )
}

export default TypingBar