import { makeStyles } from '@material-ui/core'
import { useState,useMemo } from 'react'
import { useSelector,useDispatch } from 'react-redux'

import ForwardSearch from './ForwardSearch'
import ForwardList from './ForwardList'
import { asyncGetChatById } from '../../../../../redux/chat/operations'
import { actionRightIsOpen,actionScrollChat,actionOpenPinned } from '../../../../../redux/control/action'
import { getStateMemo } from '../../../../../redux/chats/selector'
import { getSort } from '../../../../../redux/authorization/selector'
import { TMessage } from '../../../../../typescript/redux/messages/types'
import { sortByRecent,timeStampFilter } from '../../../../../helpers'

const useStyles = makeStyles({
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
    zIndex: 100,
    backgroundColor: 'rgba(104, 105, 104, 0.6)',
    overflowY: 'hidden',
  },  
  container: {
    backgroundColor: 'white',
    width: '22vw',
    position: 'absolute',
    top: '15vh',
    height:'70vh',
    left: '39vw',
    display: 'flex',
    flexWrap: 'wrap',
    alignItems: 'start',
    alignContent:'start',
    borderRadius:10,
  }
})

interface IForwardSearchList {
  setModalForward: React.Dispatch<React.SetStateAction<boolean>>,
  setIsForward: React.Dispatch<React.SetStateAction<TMessage | undefined>>,
  companionId: string,
}
const ForwardSearchList = ({setModalForward,setIsForward,companionId}:IForwardSearchList) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const sort = useSelector(getSort)
  const { total,chats } = useSelector(getStateMemo)
  const [value, setValue] = useState<string>('')
  const [date, setDate] = useState<any>('');
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>): void => setValue(e.target.value)
  const handleCloseForwardModal = (e: any) => {
    const id = e.target.id
    if (id === 'overlay' || id === 'cancel') {
      setModalForward(false)
      setIsForward(undefined)
    }
  }
  const handleForwardTo = (newCompanionId: string) => {
    setModalForward(false)
    dispatch(actionRightIsOpen(''))
    dispatch(actionOpenPinned(false))
    dispatch(asyncGetChatById(newCompanionId))
    setIsForward((prevState) => 
      prevState ? { ...prevState, companionIdForwardToAndFrom: newCompanionId } : prevState)
    if (companionId !== newCompanionId) setTimeout(() => dispatch(actionScrollChat(true)), 500)
  }

  const filteredAndSorted = useMemo(() => {
      return sortByRecent(chats,sort).filter((el) => {
      const credentials = el.name + ' ' + el.lastName
      if (!date) {
         return credentials.toLowerCase().includes(value.toLowerCase())
      } else if (credentials.toLowerCase().includes(value.toLowerCase())
        &&timeStampFilter(date) === timeStampFilter(el.lastMessageCreatedAt ?
        el.lastMessageCreatedAt : el.createdAt)) {
        return el
      } else return undefined
    })
  }, [chats, date, value, sort])  

  return (
    <div onClick={handleCloseForwardModal} className={classes.overlay} id='overlay'>
      <div className={classes.container}>
        <ForwardSearch handleSearch={handleSearch} value={value} total={total}
          sort={sort} date={date} setDate={setDate}/>
        <ForwardList value={value} date={date} filteredAndSorted={filteredAndSorted} handleForwardTo={handleForwardTo}/>
      </div>
    </div>
  )
}

export default ForwardSearchList