import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { styled } from '@mui/material/styles';
import IconButton from '@mui/material/IconButton';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import LogoutIcon from '@mui/icons-material/Logout';
import MoreVertIcon from '@mui/icons-material/MoreVert';

import { asyncLogout } from '../../../../../../redux/authorization/operations';

const StyledMenu = styled((props:any) => (
  <Menu
    elevation={0}
    anchorOrigin={{
      vertical: 'top',
      horizontal: 'right',
    }}
    transformOrigin={{
      vertical: 'bottom',
      horizontal: 'right',
    }}
    {...props}
  />
))(({ theme }:any) => ({
  '& .MuiPaper-root': {
    borderRadius: 10,
    marginTop: theme.spacing(5),
    minWidth: 180,
    color:
      theme.palette.mode === 'light' ? 'rgb(55, 65, 81)' : theme.palette.grey[500],
    boxShadow:
      'rgb(255, 255, 255) 0px 0px 0px 0px, rgba(0, 0, 0, 0.05) 0px 0px 0px 1px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px',
    '& .MuiMenu-list': {
      padding: '4px 4px',
    },
    '& .MuiMenuItem-root': {
      marginBottom: theme.spacing(1),
      '& .MuiSvgIcon-root': {
        fontSize: 21,
        color: theme.palette.text.secondary,
        marginRight: theme.spacing(4),
      }
    },
  },
}));

const MenuList = () => {
  const dispatch = useDispatch()
  const [anchorEl, setAnchorEl] = useState<any>(null);
  const open = Boolean(anchorEl);
  const handleClick = (e: React.MouseEvent<HTMLButtonElement>): void =>
    setAnchorEl(e.currentTarget)

  const handleClose = (type: string | undefined): void => {
    if (type === 'logout') dispatch(asyncLogout())
    setAnchorEl(null)
  }
  
  return (
    <>
      <IconButton onClick={handleClick} aria-label="delete"
        style={{marginLeft:5}} size="medium">
        <MoreVertIcon fontSize='medium'/>
      </IconButton>
      <StyledMenu
        id="demo-positioned-menu"
        aria-labelledby="demo-positioned-button"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        <MenuItem style={{fontWeight:500}}  onClick={() => handleClose('logout')}>
            <LogoutIcon/>
            Log Out
        </MenuItem>        
      </StyledMenu>
    </>
  );
}

export default MenuList