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

import ArrowBack from "./ArrowBack";
import SendMessage from "./SendMessage";
import MessageLeftText from './Messages/MessageLeftText'
import MessageLeftImage from './Messages/MessageLeftImage'
import MessageLeftAudio from './Messages/MessageLeftAudio'
import MessageLeftVideo from './Messages/MessageLeftVideo'
import MessageLeftFile from "./Messages/MessageLeftFile";
import MessageRightText from './Messages/MessageRightText'
import MessageRightImage from './Messages/MessageRightImage'
import MessageRightAudio from './Messages/MessageRightAudio'
import MessageRightVideo from './Messages/MessageRightVideo'
import MessageRightFile from "./Messages/MessageRightFile";
import MessageTime from "./Messages/MessageTime";
import AlertInfo from "../../../reusableComponents/AlertInfo";
import { getMessagesMemo } from '../../../../redux/messages/selector'
import { getNumber } from '../../../../redux/authorization/selector'
import { getChat } from '../../../../redux/chat/selector'
import { getScroll } from '../../../../redux/control/selector'
import { actionScroll } from '../../../../redux/control/action'
import { asyncGetMessagesById } from '../../../../redux/messages/operations'
import { seenChat } from "../../../../api-data";
import { timeStampFilter } 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',
  },
  messagesEmpty: {
      overflowY: "hidden",
      width: "100%",
      display: "flex",
      justifyContent: 'center',
      paddingTop: 30,
  },  
    messagesBody: {
      width: "60%",
  },  
});

const ChatBar = () => {
  const classes = useStyles();
  const dispatch = useDispatch()
  const messages = useSelector(getMessagesMemo)
  const userNumber = useSelector(getNumber)
  const { companionId,total } = useSelector(getChat)
  const scroll = useSelector(getScroll)
  const [isArrow, setIsArrow] = useState<boolean>(false)
  const [isScroll, setIsScroll] = useState<boolean>(true)
  const [isNew, setIsNew] = useState<{new:number,mute:boolean}>({new:0,mute:false})
  const divRef = useRef<any | null>(null)
  let time:any
  const handleScrollTo = () => {
     divRef.current&&divRef.current.scrollTo({
     top: divRef.current.scrollHeight,
     behavior: 'smooth'
     })
  }

  const handleScroll = useCallback(({ target }: any) => {
    isScroll&&setIsScroll(false)
    const different = target.scrollHeight - target.scrollTop
    if (different < 900) seenChat(companionId)
    setIsArrow(different < 1300 ? false : true)
  }, [isScroll, companionId])
  
  const debouncedHandleScroll = debounce(handleScroll, 300)
  
  useEffect(() => {
    if (scroll) {
      dispatch(asyncGetMessagesById(companionId, handleScrollTo))
      dispatch(actionScroll(false))
    }
  }, [dispatch,scroll, companionId])  

  useEffect(() => {
    dispatch(asyncGetMessagesById(companionId, handleScrollTo))
    const handleReset = () => {
      dispatch(asyncGetMessagesById(companionId, null))
      const arr: any = localStorage.getItem('isNew')
      if(arr) setIsNew(JSON.parse(arr))
    }
    const idInterval = setInterval(handleReset, 3000);
    return () => clearInterval(idInterval);
  }, [dispatch, companionId]);

  useEffect(() => {
    const scrollHeight = divRef.current.scrollHeight
    const clientHeight = divRef.current.clientHeight
    if(isScroll&&scrollHeight === clientHeight) seenChat(companionId)
  }, [isScroll, companionId, total]);

  return (
    <div className={classes.container} >
      <ArrowBack isArrow={isArrow} isNew={isNew} handleScrollTo={handleScrollTo}/>
      <div ref={divRef} onScroll={debouncedHandleScroll}
        className={messages.length > 0 ? classes.messagesScroll : classes.messagesEmpty}>
        <div className={classes.messagesBody}>
        {messages.length > 0 ? messages.map(({ message, name, lastName, color,
          updatedAt, createdAt,number, type,fullType }) => {
          let isTime
          if (!time) {
            isTime = true
            time = updatedAt
          } else if (timeStampFilter(time) !== timeStampFilter(updatedAt)) {
            time = updatedAt
            isTime = true
          }
          const url = `http://localhost:3000/${message}`
          if (number !== userNumber) {
            if (type === 'text') return (<div key={createdAt}>
              {isTime&&<MessageTime  message={timeStampFilter(updatedAt)}/>}
               <MessageLeftText
               message={message}
               updatedAt={updatedAt}
               name={name}
               lastName={lastName}
                 /></div>)
            if (type === 'image') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageLeftImage   
                url={url}
                updatedAt={updatedAt}
                color={color}
                message={message}
                messages={messages}
                fullType={fullType}
                  /></div>)
            if (type === 'audio') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageLeftAudio    
                url={url}
                updatedAt={updatedAt}
                fullType={fullType}
                  /></div>)
            if (type === 'video') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageLeftVideo    
                url={url}
                updatedAt={updatedAt}
                fullType={fullType}
                  /></div>)
            if (type) return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageLeftFile   
                url={url}
                updatedAt={updatedAt}
                type={type}
                  /></div>)             
          } else {
            if (type === 'text') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageRightText   
                message={message}
                updatedAt={updatedAt}
                name={name}
                lastName={lastName} 
                  /></div>)
            if (type === 'image') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageRightImage   
                url={url}
                updatedAt={updatedAt}
                color={color}
                message={message}
                messages={messages}
                fullType={fullType}
                  /></div>)
            if (type === 'audio') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                <MessageRightAudio    
                url={url}
                updatedAt={updatedAt}
                fullType={fullType}
                  /></div>)
            if (type === 'video') return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                 <MessageRightVideo  
                 url={url}
                 updatedAt={updatedAt}
                 fullType={fullType}
                   /></div>)
            if (type) return (<div key={createdAt}>
              {isTime&&<MessageTime message={timeStampFilter(updatedAt)}/>}
                 <MessageRightFile  
                 url={url}
                 updatedAt={updatedAt}
                 type={type}
                   /></div>)            
          }
        }) : <AlertInfo name='You do not have messages yet!' />}
        </div>
      </div>  
    <SendMessage isArrow={isArrow} handleScrollTo={handleScrollTo}/>   
    </div>
  );
}

export default ChatBar