import { makeStyles } from "@material-ui/core/styles";
import { useState, useEffect, useCallback, useMemo } from "react";
import { useSelector,useDispatch } from "react-redux";

import ArrowBack from "./ArrowBack";
import SendMessage from "./SendMessage";
import UnpinBar from "./UnpinBar";
import MessageLeftCall from "./Messages/MessageLeftCall";
import MessageLeftDeleted from "./Messages/MessageLeftDeleted";
import MessageLeftText from './Messages/MessageLeftText'
import MessageLeftReply from "./Messages/MessageLeftReply";
import MessageLeftForward from "./Messages/MessageLeftForward";
import MessageLeftImage from './Messages/MessageLeftImage'
import MessageLeftAudio from './Messages/MessageLeftAudio'
import MessageLeftVideo from './Messages/MessageLeftVideo'
import MessageLeftFile from "./Messages/MessageLeftFile";
import MessageRightCall from "./Messages/MessageRightCall";
import MessageRightDeleted from "./Messages/MessageRightDeleted";
import MessageRightText from './Messages/MessageRightText'
import MessageRightReply from "./Messages/MessageRightReply";
import MessageRightForward from "./Messages/MessageRightForward";
import MessageRightImage from './Messages/MessageRightImage'
import MessageRightAudio from './Messages/MessageRightAudio'
import MessageRightVideo from './Messages/MessageRightVideo'
import MessageRightFile from "./Messages/MessageRightFile";
import MessageDivider from "./Messages/MessageDivider";
import AlertInfo from "../../../reusableComponents/AlertInfo";
import ForwardSearchList from "./ForwardSearchList";
import { getMessagesMemo } from '../../../../redux/messages/selector'
import { getAuthorizationState } from '../../../../redux/authorization/selector'
import { getChat } from '../../../../redux/chat/selector'
import { getScrollChat } from '../../../../redux/control/selector'
import { actionScrollChat,actionOpenPinned,actionRightIsOpen } from '../../../../redux/control/action'
import { asyncGetMessagesById } from '../../../../redux/messages/operations'
import { asyncGetChatById,asyncStartChatById } from "../../../../redux/chat/operations";
import { seenChat } from "../../../../api-data";
import { TPinnedMessages } from "../../../../typescript/redux/pinnedMessages/types";
import { TMessage } from "../../../../typescript/redux/allMessages/types"; 
import { timeStampFilter,prodAwsS3,refreshAppTime } from "../../../../helpers";
const debounce = require('lodash.debounce');

const useStyles = makeStyles({   
  container: {
      height: '93vh',
      width: "100%",
      display: "flex",
      alignItems: "center",
      alignContent:"center",
      flexDirection: "column",
      position: "relative",
    },
  messagesScroll: {
      paddingTop: 30,
      overflowY: "scroll",
      maxHeight: '83vh',
      width: "100%",
      display: "flex",
      justifyContent: 'center',
      '&::-webkit-scrollbar': {
        width: '0.4em'
       },
     '&::-webkit-scrollbar-track': {
       boxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
       webkitBoxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
       backgroundColor: '#eceeec',
      },
     '&::-webkit-scrollbar-thumb': {
       backgroundColor: '#ccc8c8',
      },
     "&::-webkit-scrollbar-thumb:focus": {
       backgroundColor: "#959595",
      },
      "&::-webkit-scrollbar-thumb:active": {
       backgroundColor: "#959595",
     },
  },
  messagesEmpty: {
      overflowY: "hidden",
      width: "100%",
      display: "flex",
      justifyContent: 'center',
      paddingTop: 30,
  },  
  messagesBody: {
      width: "60%",
  },   
});

interface IChatBar {
  chatDivRef: any | null,
  selectedArr: string[] | [],
  setSelectedArr: React.Dispatch<React.SetStateAction<string[] | []>>,
  isSomeSelected: boolean,
  setIsSomeSelected: React.Dispatch<React.SetStateAction<boolean>>,
  openPinned: boolean,
  pinnedMessagesMemo: TPinnedMessages,
  handleUnpinAll: () => void,
}

const ChatBar = ({chatDivRef,selectedArr,setSelectedArr,isSomeSelected,setIsSomeSelected,openPinned,pinnedMessagesMemo,handleUnpinAll}:IChatBar) => {
  const classes = useStyles();
  const dispatch = useDispatch()
  const messagesMemo = useSelector(getMessagesMemo)
  const { number:userNumber,nightMode,silentMode} = useSelector(getAuthorizationState)
  const { companionId,total,seen,mute,seenCompanion,number:chatNumber } = useSelector(getChat)
  const scrollChat = useSelector(getScrollChat)
  const [isArrow, setIsArrow] = useState<boolean>(false)
  const [isNew, setIsNew] = useState<{ new: number, mute: boolean }>({ new: 0, mute: false })
  const [isReply, setIsReply] = useState<TMessage | undefined>(undefined)
  const [isForward, setIsForward] = useState<TMessage | undefined>(undefined)
  const [isEdit, setIsEdit] = useState<TMessage | undefined>(undefined)
  const [modalForward, setModalForward] = useState<boolean>(false)
  let time: any
  let tongue: any
  let unread: any
  const getSeconds = (createdAt:string) => Math.round(new Date(createdAt).getTime()/ 1000)
  const isSelected = (_id: string) => selectedArr.some((el: string) => el === _id)  
  const handleSelected = (_id: string) => {
    !isSomeSelected&&setIsSomeSelected(true)
    if (selectedArr.some((el: string) => el === _id)) 
      setSelectedArr(selectedArr.filter((el:string) => el !== _id))
     else setSelectedArr([...selectedArr,_id])
  }

  const handleReply = (_id: string) => {
    openPinned && dispatch(actionOpenPinned(false))
    isEdit&&setIsEdit(undefined)
    setIsReply(renderArr.find((el) => el._id ===_id))
  }
  
  const handleForward = (_id: string) => {
    openPinned && dispatch(actionOpenPinned(false))
    isReply && setIsReply(undefined)
    isEdit&&setIsEdit(undefined)
    setIsForward(renderArr.find((el) => el._id === _id))
    setModalForward(true)
  }

  const handleEdit = (_id: string) => {
    openPinned && dispatch(actionOpenPinned(false))
    isReply && setIsReply(undefined)
    setIsEdit(renderArr.find((el) => el._id ===_id))
  }   
 
  const handleScrollTo = useCallback(() => {
     chatDivRef.current&&chatDivRef.current.scrollTo({
     top: chatDivRef.current.scrollHeight,
     behavior: 'smooth'
     })
  },[chatDivRef])

  const handleScroll = useCallback(({ target:{scrollHeight,scrollTop,clientHeight}}: any) => {
    const different = scrollHeight - Math.floor(scrollTop)
    const reached = different - clientHeight
    if (total !== seen&&reached < 10 && !openPinned) seenChat(companionId)
    setIsArrow(different === clientHeight ? false : true)
  }, [total,seen, companionId,openPinned])
  
  const debouncedHandleScroll = debounce(handleScroll, 300)

  const renderArr = useMemo(() => {
    return !openPinned ? messagesMemo : pinnedMessagesMemo
  }, [messagesMemo, pinnedMessagesMemo, openPinned])
  
  const handleScrollToTheMessage = (_id:string) => {
    const childNodes = chatDivRef.current.childNodes[0].childNodes
    let toScrollNode = [...childNodes].find((el: any) => el.id === _id)
    if (toScrollNode) {
      toScrollNode = [...toScrollNode.childNodes].slice(-1)[0]
      toScrollNode.style.backgroundColor = 'rgba(70, 70, 70, 0.4)'
      toScrollNode.style.boxShadow = '0px 0px 6px 0px #ffffff'
      toScrollNode.scrollIntoView({ behavior: 'smooth' })
      setTimeout(() => {
        toScrollNode.style.backgroundColor = 'unset'
        toScrollNode.style.boxShadow = 'unset'
      }, 2000)
    }
  }  

  const handleScrollToTheChat = (companionIdForwardToAndFrom:string,oldId:string) => {
    if (companionId === companionIdForwardToAndFrom) return handleScrollToTheMessage(oldId)
    dispatch(actionRightIsOpen(''))
    dispatch(actionOpenPinned(false))
    dispatch(asyncStartChatById(companionIdForwardToAndFrom))
    setTimeout(() => handleScrollToTheMessage(oldId), 2000)
  }
  
  const handleOpenTheChat = (companionIdForwardToAndFrom: string | null) => {
    if (companionIdForwardToAndFrom&&companionId !== companionIdForwardToAndFrom) {
      dispatch(actionRightIsOpen(''))
      dispatch(actionOpenPinned(false))
      dispatch(asyncStartChatById(companionIdForwardToAndFrom))
    }
  }
  
  useEffect(() => {
    if (scrollChat) {
      dispatch(asyncGetMessagesById(companionId, handleScrollTo))
      dispatch(actionScrollChat(false))
    }
  }, [dispatch,handleScrollTo, scrollChat, companionId])
  
  useEffect(() => {
    const handleReset = () => {
      dispatch(asyncGetChatById(companionId))
      dispatch(asyncGetMessagesById(companionId, null))
    }
    handleReset()
    const idInterval = setInterval(handleReset, refreshAppTime);
    return () => clearInterval(idInterval);
  }, [dispatch, companionId]);
  
  useEffect(() => {
     setIsNew({ new:total-seen,mute})
  }, [total, seen, mute]);
  
  useEffect(() => {
    if (chatDivRef.current&&openPinned) {
      const { scrollHeight, clientHeight } = chatDivRef.current
      if (scrollHeight === clientHeight && isArrow) setIsArrow(false)
    }
  }, [chatDivRef,openPinned,pinnedMessagesMemo.length, isArrow]);  

  useEffect(() => {
    const handleReset = () => {
      if (chatDivRef.current&&!openPinned) {
         const { scrollHeight, clientHeight } = chatDivRef.current
        if (total !== seen && scrollHeight === clientHeight) seenChat(companionId)
       }
    }
    const idInterval = setInterval(handleReset, refreshAppTime);
    return () => clearInterval(idInterval);
  }, [total, seen, chatDivRef, companionId, openPinned]);
  
  return (
    <div className={classes.container} >
      <ArrowBack isArrow={isArrow} isNew={isNew} handleScrollTo={handleScrollTo} openPinned={openPinned}/>
      {isForward && modalForward && <ForwardSearchList setModalForward={setModalForward}
            setIsForward={setIsForward} companionId={companionId}/>}
      <div id={companionId} ref={chatDivRef} onScroll={debouncedHandleScroll}
        className={messagesMemo.length > 0 ? classes.messagesScroll : classes.messagesEmpty}>
        <div className={classes.messagesBody}>
        {messagesMemo.length > 0 ? renderArr.map(({ replyMessage,message, name, lastName,avatarUrl,color,pinned,
          createdAt, number, type, fullType, replyName, replyLastName, replyCaption, caption, emoji, emojiCompanion,
          _id, oldId, forwardName, forwardLastName, companionIdForwardToAndFrom, forwardMessage, forwardCaption, edited,
          deleted, initiator, reject, duration }, i) => {
          const watched = seenCompanion - (i + 1) < 0 ? false : true
          let isUnread
          let isTime
          let isTongue = false
          const nextTongue = renderArr[i + 1]
          if (!unread && chatNumber === number&& seen - (i + 1) < 0) {
            isUnread = true
            unread = true
          }
          if (!time) {
            isTime = true
            time = createdAt
          } else if (timeStampFilter(time) !== timeStampFilter(createdAt)) {
            time = createdAt
            isTime = true
          }          
          if (!tongue&&nextTongue&&nextTongue.number === number) {
            if (getSeconds(nextTongue.createdAt) - getSeconds(createdAt) < 600) {
              isTongue = false
            } else {
              isTongue = true
            }
            tongue = number
          } else if (!tongue&&nextTongue&&nextTongue.number !== number) {
            isTongue = true
            tongue = null
          } else if (tongue&&nextTongue&&tongue === number&&nextTongue.number === number) {
            if (getSeconds(nextTongue.createdAt) - getSeconds(createdAt) < 600) {
              isTongue = false
            } else {
              isTongue = true
            }
            tongue = number
          } else if (tongue&&nextTongue&&tongue === number&&nextTongue.number !== number) {
            isTongue = true
            tongue = null
          } else if (tongue&&!nextTongue&&tongue === number) {
            isTongue = true
            tongue = null
          } else if (tongue&&!nextTongue&&tongue !== number) {
            isTongue = false
            tongue = number
          }
          if(renderArr.length-1 === i) isTongue = true
          if (nextTongue && timeStampFilter(nextTongue.createdAt) !== timeStampFilter(createdAt)) {
            isTongue = true
          }
          const url = `${prodAwsS3}/${message}`
          const urlForward = `${prodAwsS3}/${forwardMessage}`
          const urlReply = `${prodAwsS3}/${replyMessage}`
          if (number !== userNumber) {
            if (type === 'text' && duration !== null) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}> 
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
              <MessageLeftCall
               message={message}
               initiator={initiator}
               reject={reject}
               duration={duration}
               tongue={isTongue}
               watched={!unread}
               edited={edited}
               avatarUrl={avatarUrl}
               color={color}
               createdAt={createdAt}
               name={name}
               lastName={lastName}
               caption={caption}
               emoji={emoji}
               emojiCompanion={emojiCompanion}
               pinned={pinned}
               isSomeSelected={isSomeSelected}
               isSelected={isSelected}
               handleSelected={handleSelected}
               _id={_id}
               nightMode={nightMode}
               handleReply={handleReply}
               handleForward={handleForward} 
               /></div>)            
            if (type === 'text' && !oldId && !companionIdForwardToAndFrom && !deleted) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}> 
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
              <MessageLeftText
               message={message}
               tongue={isTongue}
               watched={!unread}
               edited={edited}
               avatarUrl={avatarUrl}
               color={color}
               createdAt={createdAt}
               name={name}
               lastName={lastName}
               caption={caption}
               emoji={emoji}
               emojiCompanion={emojiCompanion}
               pinned={pinned}
               isSomeSelected={isSomeSelected}
               isSelected={isSelected}
               handleSelected={handleSelected}
               _id={_id}
               nightMode={nightMode}
               handleReply={handleReply}
               handleForward={handleForward} 
               /></div>)
            if (type === 'text' && deleted) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}> 
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
               <MessageLeftDeleted
                tongue={isTongue}
                watched={watched}
                edited={edited}
                companionIdForwardToAndFrom={companionIdForwardToAndFrom}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                forwardReplyName={companionIdForwardToAndFrom?forwardName:replyName}
                forwardReplyLastName={companionIdForwardToAndFrom?forwardLastName:replyLastName}
                message={message}
                createdAt={createdAt}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                handleOpenTheChat={handleOpenTheChat}
                 /></div>)                 
            if (type === 'text' && companionIdForwardToAndFrom) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}> 
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
               <MessageLeftForward
                url={urlForward}
                companionIdForwardToAndFrom={companionIdForwardToAndFrom}
                oldId={oldId}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                forwardName={forwardName}
                forwardLastName={forwardLastName}
                forwardMessage={forwardMessage}
                forwardCaption={forwardCaption}
                message={message}
                createdAt={createdAt}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                fullType={fullType}
                handleScrollToTheChat={handleScrollToTheChat}
                 /></div>)  
            if (type === 'text' && oldId) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}> 
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
               <MessageLeftReply
                url={urlReply}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                replyMessage={replyMessage}
                message={message}
                createdAt={createdAt}
                name={name}
                lastName={lastName}
                replyName={replyName}
                replyLastName={replyLastName}
                replyCaption={replyCaption}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                fullType={fullType}
                handleScrollToTheMessage={handleScrollToTheMessage}
                oldId={oldId}
                /></div>)                             
            if (type === 'image') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageLeftImage   
                url={url}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                createdAt={createdAt}
                fullType={fullType}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                name={name}
                lastName={lastName}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                  /></div>)
            if (type === 'audio') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageLeftAudio    
                url={url}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                createdAt={createdAt}
                fullType={fullType}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                  /></div>)
            if (type === 'video') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageLeftVideo    
                url={url}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                createdAt={createdAt}
                fullType={fullType}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}              
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                  /></div>)
            if (type) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageLeftFile   
                url={url}
                tongue={isTongue}
                watched={!unread}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                createdAt={createdAt}
                type={type}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}              
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                  /></div>)             
          } else {
            if (type === 'text' && duration !== null) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageRightCall   
                message={message}
                initiator={initiator}
                reject={reject}
                duration={duration}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                createdAt={createdAt}
                name={name}
                lastName={lastName}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                /></div>)            
            if (type === 'text' && !oldId && !companionIdForwardToAndFrom && !deleted) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageRightText   
                message={message}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                createdAt={createdAt}
                name={name}
                lastName={lastName}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                /></div>)
            if (type === 'text' && deleted) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
              <MessageRightDeleted
                tongue={isTongue}
                watched={watched}
                edited={edited}
                companionIdForwardToAndFrom={companionIdForwardToAndFrom}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                forwardReplyName={companionIdForwardToAndFrom?forwardName:replyName}
                forwardReplyLastName={companionIdForwardToAndFrom?forwardLastName:replyLastName}
                message={message}
                createdAt={createdAt}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                handleOpenTheChat={handleOpenTheChat}
                  /></div>)                 
            if (type === 'text' && companionIdForwardToAndFrom) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
              <MessageRightForward
                url={urlForward}
                oldId={oldId}
                companionIdForwardToAndFrom={companionIdForwardToAndFrom}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                forwardName={forwardName}
                forwardLastName={forwardLastName}
                forwardMessage={forwardMessage}
                forwardCaption={forwardCaption}
                message={message}
                createdAt={createdAt}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                fullType={fullType}
                handleScrollToTheChat={handleScrollToTheChat}
                  /></div>) 
            if (type === 'text' && oldId) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
              <MessageRightReply
                url={urlReply}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                replyMessage={replyMessage}
                message={message}
                createdAt={createdAt}
                name={name}
                lastName={lastName}
                replyName={replyName}
                replyLastName={replyLastName}
                replyCaption={replyCaption}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}                
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                fullType={fullType}
                handleScrollToTheMessage={handleScrollToTheMessage}
                oldId={oldId}
                /></div>)                             
            if (type === 'image') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageRightImage   
                url={url}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                createdAt={createdAt}
                fullType={fullType}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}
                _id={_id}
                name={name}
                lastName={lastName}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                  /></div>)
            if (type === 'audio') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                <MessageRightAudio    
                url={url}
                tongue={isTongue}
                watched={watched}
                edited={edited}
                avatarUrl={avatarUrl}
                color={color}
                name={name}
                lastName={lastName}
                createdAt={createdAt}
                fullType={fullType}
                caption={caption}
                emoji={emoji}
                emojiCompanion={emojiCompanion}
                pinned={pinned}
                isSomeSelected={isSomeSelected}
                isSelected={isSelected}
                handleSelected={handleSelected}
                _id={_id}
                nightMode={nightMode}
                handleReply={handleReply}
                handleForward={handleForward}
                handleEdit={handleEdit}
                  /></div>)
            if (type === 'video') return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                 <MessageRightVideo  
                 url={url}
                 tongue={isTongue}
                 watched={watched}
                 edited={edited}
                 avatarUrl={avatarUrl}
                 color={color}
                 name={name}
                 lastName={lastName}
                 createdAt={createdAt}
                 fullType={fullType}
                 caption={caption}
                 emoji={emoji}
                 emojiCompanion={emojiCompanion}
                 pinned={pinned}
                 isSomeSelected={isSomeSelected}
                 isSelected={isSelected}
                 handleSelected={handleSelected}
                 _id={_id}
                 nightMode={nightMode}
                 handleReply={handleReply}
                 handleForward={handleForward}
                 handleEdit={handleEdit}
                   /></div>)
            if (type) return (<div key={createdAt} id={_id} style={{borderRadius: 7}}>
              {isTime&&<MessageDivider message={timeStampFilter(createdAt)}/>}
              {isUnread&&<MessageDivider message='Unread Messages'/>}
                 <MessageRightFile  
                 url={url}
                 tongue={isTongue}
                 watched={watched}
                 edited={edited}
                 avatarUrl={avatarUrl}
                 color={color}
                 name={name}
                 lastName={lastName}
                 createdAt={createdAt}
                 type={type}
                 caption={caption}
                 emoji={emoji}
                 emojiCompanion={emojiCompanion}
                 pinned={pinned}
                 isSomeSelected={isSomeSelected}
                 isSelected={isSelected}
                 handleSelected={handleSelected}
                 _id={_id}
                 nightMode={nightMode}
                 handleReply={handleReply}
                 handleForward={handleForward}
                 handleEdit={handleEdit}
                   /></div>)            
          }
        }) : <AlertInfo name='You do not have messages yet!' />}
        </div>
      </div>
      {!openPinned && !isSomeSelected && <SendMessage isArrow={isArrow} silentMode={silentMode} isReply={isReply} setIsReply={setIsReply}
        isForward={isForward} setIsForward={setIsForward}
        isEdit={isEdit} setIsEdit={setIsEdit}
        modalForward={modalForward} handleScrollToTheMessage={handleScrollToTheMessage}/>}
      {openPinned&&!isSomeSelected&&<UnpinBar pinnedMessagesMemo={pinnedMessagesMemo} handleUnpinAll={handleUnpinAll} />}
    </div>
  );
}

export default ChatBar