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 { getIsOpen } from '../../../../redux/control/selector';
import { sortByRecent,handleSort,timeStampFilter } from '../../../../helpers';
import { asyncStartChatById } from '../../../../redux/chat/operations';
import { actionIsOpen } from '../../../../redux/control/action';
import { TAllMessages } from '../../../../typescript/redux/allMessages/types';
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>,
}

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

    const handleListItemClick = (companionId: string) => {
      isOpen&&dispatch(actionIsOpen(''))
      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
      }
    })
      
    const filteredMessages = (arr: TAllMessages) => arr.filter((el) => {
    if (!date) {
      if (!el.fullType && el.message.toLowerCase().includes(value.toLowerCase())) {
        return el
      }
      if (el.fullType && el.fullType.toLowerCase().includes(value.toLowerCase())) {
        return el
      }
    } else {
      if (!el.fullType && el.message.toLowerCase().includes(value.toLowerCase())
        && timeStampFilter(date) === timeStampFilter(el.createdAt)) {
        return el
      }
      if (el.fullType && el.fullType.toLowerCase().includes(value.toLowerCase())
        && timeStampFilter(date) === timeStampFilter(el.createdAt)) {
        return el
      }
     }
    })
  
    useEffect(() => {
      dispatch(asyncGetAllMessages())
      dispatch(asyncGetChats())
      const handleReset = () => {
         dispatch(asyncGetAllMessages())
         dispatch(asyncGetChats())
      }
    const idInterval = setInterval(handleReset, 5000);
    return () => clearInterval(idInterval);
    }, [dispatch]);
    
    useEffect(() => {
       setDate('')
    },[setDate])
  
    const filteredAndSorted = filteredChats(sortByRecent(chats,sort))
    const allMessagesMemo = filteredMessages(handleSort('createdAt',messagesMemo,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 allMessagesMemo={allMessagesMemo} value={value} date={date}/>}
            {isActive === 2 && <MediaList allMessagesMemo={allMessagesMemo} value={value} date={date}/>}
            {isActive === 3 && <TextList allMessagesMemo={allMessagesMemo} value={value} date={date}/>}
            {isActive === 4 && <AudioList allMessagesMemo={allMessagesMemo} value={value} date={date}/>}
            {isActive === 5 && <VideoList allMessagesMemo={allMessagesMemo} value={value} date={date}/>}
    </>      
    )
}

export default SearchLists