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 { getContacts } from '../../../../../../../redux/contacts/selector'
import { getChat } from '../../../../../../../redux/chat/selector'
import { asyncGetContacts,asyncAddContact } from '../../../../../../../redux/contacts/operations';

const useStyles = makeStyles({
  container: {
    borderLeft: 'solid 0.5px #9c9c9c',
    paddingLeft: 10,
    paddingBottom: 3,
    width: 482,
    display: 'flex',
    alignContent: 'center',
    alignItems: 'center',    
  },
})

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

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

  useEffect(() => {
    const isExist = contacts.some((el) => el.number === number)
    isExist&&setIsContact(true)
  }, [contacts,number])

  return (
    <Stack className={classes.container} direction="row" spacing={40}>
      <IconButton onClick={() => dispatch(actionIsOpen(''))} aria-label="delete" size="medium">
        <CloseIcon fontSize='medium'/>
      </IconButton>
      <Typography variant="h6" color="initial" style={{marginLeft:20}}>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