import List from '@mui/material/List';
import { makeStyles } from '@material-ui/core'
import { useEffect,useRef,useCallback,useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';

import AlertInfo from '../../../reusableComponents/AlertInfo'
import ChatItem from './ChatItem';
import { notification,playNotificationWithoutPermission,sortByRecent } from '../../../../helpers'
import { getStateMemo } from '../../../../redux/chats/selector'
import { getChatMemo } from '../../../../redux/chat/selector'
import { getSilentMode } from '../../../../redux/authorization/selector'
import { asyncGetChatById } from '../../../../redux/chat/operations'
import { asyncGetChats } from '../../../../redux/chats/operations';
import { actionRightIsOpen,actionScrollChat,actionOpenPinned } from '../../../../redux/control/action'
import { TChats,TChat } from '../../../../typescript/redux/chats/types';
import { prodBaseURL,refreshAppTime } from '../../../../helpers';

const useStyles = makeStyles({
  list: {
    width: '100%',
    maxHeight: '93vh',
    overflowY: 'scroll',
  '&::-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",
    },
  },
})

interface IChatsList {
  sort: boolean,
  setDisabled: React.Dispatch<boolean>,
}

const ChatsList = ({sort,setDisabled}:IChatsList) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const chatsRef = useRef<any>(null)
  const silentMode = useSelector(getSilentMode)
  const { total, chats } = useSelector(getStateMemo)
  const chat = useSelector(getChatMemo) 
  
  const handleListItemClick = (companionId: string) => {
    dispatch(actionRightIsOpen(''))
    dispatch(actionOpenPinned(false))
    dispatch(asyncGetChatById(companionId))
    if(chat.companionId !== companionId) setTimeout(() => dispatch(actionScrollChat(true)), 500)
  }

  const handleNewMsgs = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>, companionId: string) => {
    e.stopPropagation()
    dispatch(actionRightIsOpen(''))
    dispatch(actionOpenPinned(false))
    dispatch(asyncGetChatById(companionId))
    setTimeout(() => dispatch(actionScrollChat(true)), 500)
  }

  const handleNotification = useCallback((companionId: string) => {
    dispatch(asyncGetChatById(companionId))
    dispatch(actionOpenPinned(false))
    dispatch(actionRightIsOpen(''))
    setTimeout(() => dispatch(actionScrollChat(true)), 500)
  }, [dispatch])

  const sortedChats = useMemo((): TChats => {
    const pinnedArr: any[] = []
    const sortedAndFilteredArr: TChats = sortByRecent(chats, sort)
      .filter((el: TChat) => {
      if (el.pinned === true) {
        pinnedArr.push(el)
        return undefined
      } else return el
    })
    return [...pinnedArr,...sortedAndFilteredArr]
  },[chats,sort])
  
  useEffect(() => {
    const handleReset = () => dispatch(asyncGetChats())
    handleReset()
    const idInterval = setInterval(handleReset, refreshAppTime);
    return () => clearInterval(idInterval);
  }, [dispatch]);  

  useEffect(() => {
    if (chatsRef.current) {
      chatsRef.current.forEach(({total,seen}: any,i:number) => {
        const oldDifferent = total - seen
        const chat = sortedChats[i]
        if(chat === undefined) return
        const newDifferent = chat.total - chat.seen
        if (newDifferent > oldDifferent && !chat.mute) {
          !silentMode&&playNotificationWithoutPermission(`${prodBaseURL}/telegramReceive.mp3`)
          notification(chat.name, () => handleNotification(chat.companionId))
        } 
      })
    }
    chatsRef.current = sortedChats
  }, [chat,sortedChats,handleNotification,dispatch,silentMode])

  useEffect(() => {
    setDisabled(total === '0'?true:false)
  }, [total, setDisabled])
  
  return total !== '0' ? (
    <List className={classes.list} component="nav"
      aria-label="main mailbox folders">
      {sortedChats.map((el) => <ChatItem key={el.number} chat={el}  
        handleListItemClick={handleListItemClick} handleNewMsgs={handleNewMsgs}
        id={el._id} pinned={el.pinned} selectedCompanionId={chat.companionId} />)}
    </List>
  ):<AlertInfo name='You do not have Chats yet!' />;
}

export default ChatsList