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 { useDispatch, useSelector } from 'react-redux';
import { useEffect,useRef } from 'react';

import { actionIsOpen } from '../../../../../redux/control/action'
import { getChat } from '../../../../../redux/chat/selector'
import { asyncGetChatById } from '../../../../../redux/chat/operations'
import { firstLetter,slicedWord,timeStampEU } from '../../../../../helpers'

const Credentials = () => {
  const dispatch = useDispatch()
  const { name, lastName, avatarUrl, color, online, companionId,seen,total,mute } = useSelector(getChat)
  const ref = useRef<any>(null)
    useEffect(() => {
    const handleReset = () => companionId&&dispatch(asyncGetChatById(companionId))
    const idInterval = setInterval(handleReset, 3000);
    return () => clearInterval(idInterval);
    }, [dispatch, companionId]);
  
  useEffect(() => {
    if (ref.current) {
        localStorage.setItem('isNew', JSON.stringify({ new: total - seen, mute }))
      }
    ref.current = { seen,total}
  }, [seen, total, mute]);
  
  return (
    <ListItemButton onClick={() => dispatch(actionIsOpen('credentials'))}>
      <ListItemIcon >
        <Avatar alt={name} src={avatarUrl?`http://localhost:3000/${avatarUrl}`:undefined}
              sx={{ background: color, width: 44, height: 44 }}>
              {!avatarUrl&&`${firstLetter(name)}${firstLetter(lastName)}`}
          </Avatar>
      </ListItemIcon> 
      <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
        ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
        secondaryTypographyProps={{ color: '#0379af' }} secondary={online === 'true' ?
          'online' : `last seen ${timeStampEU(online)}`} />
    </ListItemButton>
  )
}

export default Credentials