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

import AlertInfo from '../../../reusableComponents/AlertInfo'
import ContactItem from './ContactItem';
import { getState } from '../../../../redux/contacts/selector'
import { asyncGetContacts } from '../../../../redux/contacts/operations'
import { asyncStartChatById } from '../../../../redux/chat/operations'
import { getIsOpen } from '../../../../redux/control/selector'
import { actionIsOpen } from '../../../../redux/control/action';
import { handleSort } from '../../../../helpers';
import { TContacts } from '../../../../typescript/redux/contacts/types';

const useStyles = makeStyles({
  list: {
    width: '100%',
    maxHeight: '890px',
    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: any,
  sort: boolean
}
const  ContactsList = ({value,handleClick,sort} : IContactList) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const { total, contacts } = useSelector(getState)
  const isOpen = useSelector(getIsOpen)

  const handleListItemClick = (companionId:string) => {
    handleClick()
    isOpen&&dispatch(actionIsOpen(''))
    dispatch(asyncStartChatById(companionId))
  }

  const filteredContacts = () => handleSort('name',contacts,sort).filter((el:any) => {
    const credentials = el.name + ' ' + el.lastName
    if(credentials.toLowerCase().includes(value.toLowerCase())) return el
  })

  useEffect(() => {
    dispatch(asyncGetContacts())
    const handleReset = () => isOpen !== 'credentials' &&dispatch(asyncGetContacts())
    const idInterval = setInterval(handleReset, 3000);
    return () => clearInterval(idInterval);
  }, [dispatch,isOpen]);

  const arr:TContacts = filteredContacts()
  
  return total !== '0' ? (
    <List
      className={classes.list} component="nav"
      aria-label="main mailbox folders">
      {arr.length > 0 ? arr.map((contact) => <ContactItem key={contact.number}
        contact={contact} handleListItemClick={handleListItemClick} isOpen={isOpen}/>) :
        <AlertInfo name={`Can not find contact by request : ${value}`} />}
      </List>
  ):<AlertInfo name='You do not have any contact yet!' />;
}

export default ContactsList