import Stack from '@mui/material/Stack';
import IconButton from '@mui/material/IconButton';
import PersonAddAltIcon from '@mui/icons-material/PersonAddAlt';
import EditIcon from '@mui/icons-material/Edit';
import CloseIcon from '@mui/icons-material/Close';
import { makeStyles, Typography } from '@material-ui/core'
import { useDispatch, useSelector } from 'react-redux';
import { useState,useEffect } from 'react';
import { actionIsOpen } from '../../../../../../../redux/control/action'
import { getContactsMemo } from '../../../../../../../redux/contacts/selector'
import { getChat } from '../../../../../../../redux/chat/selector'
import { asyncGetContacts,asyncAddContact } from '../../../../../../../redux/contacts/operations';

const useStyles = makeStyles({
  container: {
    paddingLeft: 10,
    paddingBottom: 3,
    width: 482,
    display: 'flex',
    alignContent: 'center',
    alignItems: 'center',    
  },
  iconClose: {
    '&:hover': {
      transform: 'rotate(180deg)',
      transition: 'all 250ms ease-out ',
    }
  },  
})

const ToolBar = () => {
  const dispatch = useDispatch()
  const classes = useStyles()
  const contactsMemo = useSelector(getContactsMemo)
  const { number } = useSelector(getChat)
  const [isContact, setIsContact] = useState<boolean>(false)

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

  useEffect(() => {
    const contact = contactsMemo.find((el) => el.number === number)
     if (contact) {
      setIsContact(true)
     } else {
       setIsContact(false)
    }    
  }, [contactsMemo,number])
  
  return (
    <Stack className={classes.container} direction="row" spacing={40}>
      <IconButton onClick={() => dispatch(actionIsOpen(''))} aria-label="delete" size="medium">
        <CloseIcon className={classes.iconClose} fontSize='medium'/>
      </IconButton>
      <Typography variant="h6" color="initial" style={{marginLeft:20,color: '#474747'}}>Profile</Typography>
      <IconButton  aria-label="delete" size="medium">
        {isContact ? <EditIcon onClick={() => dispatch(actionIsOpen('edit'))} fontSize='medium' /> :
          <PersonAddAltIcon onClick={() => dispatch(asyncAddContact(number))} fontSize='medium' />}
      </IconButton>
    </Stack>
    )
}

export default ToolBar