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

import AlertInfo from '../../../reusableComponents/AlertInfo'
import ContactItem from './ContactItem';
import { getStateMemo } from '../../../../redux/contacts/selector'
import { asyncGetContacts } from '../../../../redux/contacts/operations';
import { asyncStartChatById } from '../../../../redux/chat/operations'
import { getRightIsOpen } from '../../../../redux/control/selector'
import { actionLeftIsOpen, actionRightIsOpen,actionOpenPinned } from '../../../../redux/control/action';
import { handleSort,timeStampFilter,refreshAppTime } from '../../../../helpers';
import { TContacts,TContact } from '../../../../typescript/redux/contacts/types';

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 IContactList {
  value: string,
  handleClick: () => void,
  sort: boolean,
  date: any,
  setDisabled: React.Dispatch<boolean>,
}
const  ContactsList = ({value,handleClick,sort,date,setDisabled} : IContactList) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const { total, contacts } = useSelector(getStateMemo)
  const rightIsOpen = useSelector(getRightIsOpen)

  const handleListItemClick = (companionId: string) => {
    handleClick()
    dispatch(actionRightIsOpen(''))
    dispatch(actionOpenPinned(false))
    dispatch(asyncStartChatById(companionId))
  }

  useEffect(() => {
    dispatch(actionLeftIsOpen('contacts'))
  }, [dispatch])    

  useEffect(() => {
    setDisabled(total === '0'?true:false)
  }, [total, setDisabled])
  
  useEffect(() => {
    const handleReset = () => dispatch(asyncGetContacts())
    handleReset()
    const idInterval = setInterval(handleReset, refreshAppTime);
    return () => clearInterval(idInterval);
  }, [dispatch]);

  const filteredContacts = useMemo((): TContacts => {
    const pinnedArr: any[] = []
    const sortedAndFilteredArr: TContacts = handleSort('name', contacts, sort)
      .filter((el: TContact) => {
      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.createdAt)) {
        return el
      } else return undefined
    }).filter((el: TContact) => {
      if (el.pinned === true) {
        pinnedArr.push(el)
        return undefined
      } else return el
    })
    return [...pinnedArr,...sortedAndFilteredArr]
  },[contacts,date,value,sort])  
  
  return total !== '0' ? (
    <List
      className={classes.list} component="nav"
      aria-label="main mailbox folders">
      {filteredContacts.length > 0 ? filteredContacts.map((contact) => <ContactItem key={contact.number}
        contact={contact} handleListItemClick={handleListItemClick}
        rightIsOpen={rightIsOpen} id={contact._id} pinned={contact.pinned} />) :
        <AlertInfo name={`Can not find Contact by request : ${value}`} />}
      </List>
  ):<AlertInfo name='You do not have Contact yet!' />;
}

export default ContactsList