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 { styled } from '@mui/material/styles';
import Badge from '@mui/material/Badge';
import VolumeOffIcon from '@mui/icons-material/VolumeOff';
import { makeStyles, Typography } from '@material-ui/core'
import { useState,useEffect,useRef } from 'react';
import shortid from 'shortid';
import { useSelector, useDispatch } from 'react-redux';

import AlertInfo from '../../../reusableComponents/AlertInfo'
import DoneAllIcon from '@mui/icons-material/DoneAll';
import { firstLetter, slicedWord, timeStamp,notification,playNotificationWithoutPermission } from '../../../../helpers'
import { getState } from '../../../../redux/chats/selector'
import { asyncGetChats } from '../../../../redux/chats/operations'
import { asyncStartChatById } from '../../../../redux/chat/operations'
import { actionScroll } from '../../../../redux/control/action'

const StyledBadge = styled(Badge)(({ theme }) => ({
  '& .MuiBadge-badge': {
    backgroundColor: '#44b700',
    color: '#44b700',
    boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
    '&::after': {
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      borderRadius: '50%',
      animation: 'ripple 1.2s infinite ease-in-out',
      border: '1px solid currentColor',
      content: '""',
    },
  },
  '@keyframes ripple': {
    '0%': {
      transform: 'scale(.8)',
      opacity: 1,
    },
    '100%': {
      transform: 'scale(2.4)',
      opacity: 0,
    },
  },
}));


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",
    },
  },
  listItemInnerText: {
    display: 'flex',
    alignContent: 'center',
    alignItems: 'center',
    flexWrap: 'nowrap',
  },
  listItemInnerText__icon: {
    marginLeft: 5,
    color: '#959595',
  },
  listItem_iconAvatar: {
    marginRight:10
  },
  listItem_iconRight: {
    marginRight: 10,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    flexDirection: 'column'
  },
  listItem_iconTimeChecked: {
    display: 'flex',
    flexWrap: 'nowrap',
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    marginBottom:2
  },
  listItem_iconRightBtn: {
    background: '#0ac40a',
    borderRadius: '50%',
    color: '#ffffff',
    border: 'none',
    height: 24,
    width: 24,
    textAlign: 'center',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    fontSize: 12,
    marginLeft: 'auto',
    '&:hover': {
      outline: 'solid 3px #3ee415',
    }
  },
    listItem_iconRightBtnMute: {
    background: '#a7aaa7',
    borderRadius: '50%',
    color: '#ffffff',
    border: 'none',
    height: 24,
    width: 24,
    textAlign: 'center',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    fontSize: 12,
    marginLeft: 'auto',
    '&:hover': {
      outline: 'solid 3px #cccbcb',
    }
  },
  listItem_iconRightBtnHidden: {
    background: 'inherit',
    borderRadius: '50%',
    border: 'none',
    height: 24,
    width: 24,
    textAlign: 'center',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    fontSize: 12,
    marginLeft: 'auto', 
  },
  listItem_icon_time: {
    fontSize: 12,
    marginLeft: 5,
    color: '#1b1b1b'
  },
  listItem_typing: {
    color: '#4d4d4d',
    animation: 'ripple 4s infinite ease-in-out',   
  },  
  listItem_dots: {
    color: '#1b1b1b',
    fontWeight: 'bold',
    display:'inline-block',
    fontFamily: 'monospace',
    clipPath: 'inset(0 3ch 0 0)',
    animation: `$run 2s steps(5) infinite`,   
  },
  '@keyframes run': {
    to: {
       clipPath: 'inset(0 -1ch 0 0)'
    },
  },
})

const ChatsList = () => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const ref = useRef<any>(null)
  const [selectedIndex, setSelectedIndex] = useState<number>(1);
  const { total, chats , lastMessages,lastOnline } = useSelector(getState)
 

  const handleListItemClick = (i: number, companionId: string) => {
    dispatch(asyncStartChatById(companionId))
    dispatch(actionScroll(false))
    setSelectedIndex(i);
  }

  const handleNewMsgs = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>, i: number,companionId: string) => {
    e.stopPropagation()
    dispatch(asyncStartChatById(companionId))
    dispatch(actionScroll(true))
    console.log(i,'index','clicked read new messages')
  }

  useEffect(() => {
    const handleReset = () => dispatch(asyncGetChats())
    const idInterval = setInterval(handleReset, 1500);
    return () => clearInterval(idInterval);
  }, [dispatch]);
  
  useEffect(() => {
    dispatch(asyncGetChats())
  }, [dispatch])

  useEffect(() => {
    const handleNotification= (companionId: string) => {
      dispatch(asyncStartChatById(companionId))
      dispatch(actionScroll(true))
   }
    if (ref.current) {
      ref.current.forEach(({total,seen}: any,i:number) => {
        const oldDifferent = total - seen
        const chat = chats[i]
        const newDifferent = chat.total - chat.seen
        if (newDifferent > oldDifferent && !chat.mute) {
          playNotificationWithoutPermission('http://localhost:3000/recive.mp3')
          notification(chat.name,() => handleNotification(chat.companionId))
        }
      })
    }
      ref.current = chats
  }, [chats,dispatch])  

  return total !== '0' ? (
    <List className={classes.list} component="nav"
          aria-label="main mailbox folders">
      {chats.map(({name, lastName, avatarUrl, updatedAt, color,companionId,mute,seen,total,watched,typing }, i: number) => 
          <ListItemButton
          key={shortid.generate()}
          selected={selectedIndex === i}
          onClick={() => handleListItemClick(i,companionId)}
          >
          <ListItemIcon className={classes.listItem_iconAvatar}>
            <StyledBadge overlap="circular"  variant={lastOnline[i].online === 'true'?'dot':'standard'}
                  anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}>
                 <Avatar alt={name} src={avatarUrl?`http://localhost:3000/${avatarUrl}`:undefined}
                     sx={{ background: color, width: 54, height: 54 }}>
                     {!avatarUrl&&`${firstLetter(name)}${firstLetter(lastName)}`}
                  </Avatar>
              </StyledBadge>
          </ListItemIcon> 
          <ListItemText primary={<div className={classes.listItemInnerText}>
            <span>{`${firstLetter(name)}${slicedWord(name, 15, 1)} 
             ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}</span>
            {mute&&<VolumeOffIcon className={classes.listItemInnerText__icon} fontSize='small' />}</div>}
            secondary={typing ? <span className={classes.listItem_typing}>
              typing<span className={classes.listItem_dots}>...</span></span> :
              lastMessages[i] ? slicedWord(lastMessages[i].message, 35) :
              `${firstLetter(name)}${slicedWord(name, 8, 1)} joined Telegram`}/>
          <ListItemIcon className={classes.listItem_iconRight}>
               <div className={classes.listItem_iconTimeChecked}>
                 {watched&& <DoneAllIcon style={{ color: '#18bd03' }} fontSize='small' />}
              <Typography className={classes.listItem_icon_time} variant="h6" color="initial">
                {lastMessages[i] ? timeStamp(lastMessages[i].updatedAt) :
                timeStamp(updatedAt)}</Typography>
               </div>
            {lastMessages[i] && total > seen ? <button onClick={(e) => handleNewMsgs(e, i,companionId)}
              className={mute?classes.listItem_iconRightBtnMute:classes.listItem_iconRightBtn}>{total-seen}</button> :
              <button  className={classes.listItem_iconRightBtnHidden}/>}
          </ListItemIcon>            
        </ListItemButton>)}
      </List>
  ):<AlertInfo name='You do not have any chats yet!' />;
}

export default ChatsList