import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import Avatar from '@mui/material/Avatar';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon from '@mui/material/ListItemIcon';
import { makeStyles } from '@material-ui/core'
import { useState,useEffect } from 'react';
import shortid from 'shortid';
import { useSelector,useDispatch } from 'react-redux';

import AlertInfo from '../../../reusableComponents/AlertInfo'
import { getState } from '../../../../redux/contacts/selector'
import { asyncGetContacts } from '../../../../redux/contacts/operations'
import { firstLetter, slicedWord, timeStamp } from '../../../../helpers'
import { asyncStartChatById } from '../../../../redux/chat/operations'

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",
    },
  },
  listItem_iconAvatar: {
    marginRight:10
  },
})

const  ContactsList = () => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const { total, contacts } = useSelector(getState)
  const [selectedIndex, setSelectedIndex] = useState<number>(1);  
  const handleListItemClick = async (i:number, companionId:string) => {
     setSelectedIndex(i);
     await dispatch(asyncStartChatById(companionId))
  }

  useEffect(() => {
    dispatch(asyncGetContacts())
  }, [dispatch])

  
  return total !== '0' ? (
    <List
      className={classes.list} component="nav"
      aria-label="main mailbox folders">
      {contacts.map(({name,lastName,avatarUrl,color,createdAt,companionId }, i: number) => 
        <ListItemButton
          key={shortid.generate()}
          selected={selectedIndex === i}
          onClick={() => handleListItemClick(i,companionId)}
          >
          <ListItemIcon className={classes.listItem_iconAvatar}>
            <Avatar alt={name} src={avatarUrl?`http://localhost:3000/${avatarUrl}`:undefined}
                 sx={{ background: color, width: 54, height: 54 }}>
                 {!avatarUrl&&`${firstLetter(name)}${firstLetter(lastName)}`}
              </Avatar>
          </ListItemIcon> 
          <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
               ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
               secondary={`Registered since ${timeStamp(createdAt)}`} />
        </ListItemButton>)}
      </List>
  ):<AlertInfo name='You do not have any contact yet!' />;
}

export default ContactsList