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

import ChatListRecent from './ChatListRecent'
import FilesList from './FilesList';
import MediaList from './MediaList';
import TextList from './TextList';
import AudioList from './AudioList'
import VideoList from './VideoList';
import { asyncGetAllMessages } from '../../../../redux/allMessages/operations';
import { asyncGetChats } from '../../../../redux/chats/operations';
import { getStateMemo } from '../../../../redux/chats/selector';
import { getAllMessagesMemo } from '../../../../redux/allMessages/selector';
import { getState } from '../../../../redux/control/selector';
import { sortByRecent,timeStampFilter,refreshAppTime } from '../../../../helpers';
import { asyncStartChatById } from '../../../../redux/chat/operations';
import { actionLeftIsOpen,actionRightIsOpen } from '../../../../redux/control/action';
import { TChats } from '../../../../typescript/redux/chats/types';

const useStyles = makeStyles({
container: {
  height:'7vh',
  borderBottom: 'solid 2px #dddddd',
  display: 'flex',
  justifyContent: 'space-around',
  alignContent: "center",
  alignItems:"center",
  flexWrap: 'nowrap',
  color:'rgba(0, 0, 0, 0.6)'
},
item: {
  height:'100%',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  alignContent: "center",
  alignItems: "center",
  cursor:'pointer',
},
icon: {
  fontSize: '1rem',
  lineHeight: 0,
  marginBottom: 0,
  fontWeight:600
 },
underline: {
  fontSize: '2.2rem',
  lineHeight: 0,
  },
})

interface ISearchLists {
  value: string,
  setValue: React.Dispatch<string>
  sort: boolean,
  date: any,
  setDate: React.Dispatch<any>,
  setDisabled: React.Dispatch<boolean>,
}

const SearchLists = ({ value,setValue,sort,date,setDate,setDisabled }: ISearchLists) => {
    const classes = useStyles()
    const dispatch = useDispatch()
    const { chats, total } = useSelector(getStateMemo)
    const messagesMemo = useSelector(getAllMessagesMemo)
    const {leftIsOpen,rightIsOpen} = useSelector(getState)
    const [isActive, setIsActive] = useState<number>(0)
    const handleIsActive = (newValue: number): void => {
      setIsActive(newValue)
      value && setValue('')
      date&&setDate('')
    } 

    const handleListItemClick = (companionId: string) => {
      rightIsOpen&&dispatch(actionRightIsOpen(''))
      dispatch(asyncStartChatById(companionId))
    }
    const filteredChats = (arr: TChats) => arr.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
      }
    })
  
    useEffect(() => {
       setDate('')
    }, [setDate])
  
    useEffect(() => {
      if (isActive === 0) {
          dispatch(actionLeftIsOpen('searchChats'))
      } else {
        dispatch(actionLeftIsOpen('searchAllMessages'))
        }
    }, [isActive,dispatch])  
  
    useEffect(() => {
        if (isActive === 0) setDisabled(total === '0'?true:false)
    }, [isActive,total,setDisabled])
  
    useEffect(() => {
      const handleReset = () => {
        if (leftIsOpen === 'searchChats') {
          dispatch(asyncGetChats())
        } else if (leftIsOpen === 'searchAllMessages') {
          dispatch(asyncGetAllMessages())
        }
      }
      handleReset()
      const idInterval = setInterval(handleReset, refreshAppTime);
      return () => clearInterval(idInterval);
    }, [leftIsOpen,dispatch]);
    
  
    const filteredAndSorted = filteredChats(sortByRecent(chats,sort))
    return (
    <>
        <div className={classes.container}>
          <div className={classes.item} style={{color:isActive === 0?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(0)}>
            <span className={classes.icon}>Chats</span>
            <span className={classes.underline}>___</span>
          </div>
          <div className={classes.item} style={{color:isActive === 1?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(1)}>
            <span className={classes.icon}>Files</span>
            <span className={classes.underline}>___</span>
          </div>
          <div className={classes.item} style={{color:isActive === 2?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(2)}>
            <span className={classes.icon}>Media</span>
            <span className={classes.underline}>___</span>
          </div>
          <div className={classes.item} style={{color:isActive === 3?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(3)}>
            <span className={classes.icon}>Text</span>
            <span className={classes.underline}>___</span>
          </div>
          <div className={classes.item} style={{color:isActive === 4?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(4)}>
            <span className={classes.icon}>Audio</span>
            <span className={classes.underline}>___</span>
          </div>
          <div className={classes.item} style={{color:isActive === 5?'#1976d2':"rgba(0, 0, 0, 0.6)"}}
            onClick={() => handleIsActive(5)}>
            <span className={classes.icon}>Video</span>
            <span className={classes.underline}>___</span>
          </div>          
      </div>
            {isActive === 0 && <ChatListRecent value={value} date={date}
              filteredAndSorted={filteredAndSorted} handleListItemClick={handleListItemClick} />}
            {isActive === 1 && <FilesList messagesMemo={messagesMemo} value={value} date={date} sort={sort} setDisabled={setDisabled}/>}
            {isActive === 2 && <MediaList messagesMemo={messagesMemo} value={value} date={date} sort={sort} setDisabled={setDisabled}/>}
            {isActive === 3 && <TextList  messagesMemo={messagesMemo} value={value} date={date} sort={sort} setDisabled={setDisabled}/>}
            {isActive === 4 && <AudioList messagesMemo={messagesMemo} value={value} date={date} sort={sort} setDisabled={setDisabled}/>}
            {isActive === 5 && <VideoList messagesMemo={messagesMemo} value={value} date={date} sort={sort} setDisabled={setDisabled}/>}
    </>      
    )
}

export default SearchLists