import React, { useState } from 'react';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import { useStyles } from './styles/styles';
import { User } from 'common/types';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import IconButton from '@material-ui/core/IconButton';
import ClickAwayListener from '@material-ui/core/ClickAwayListener';

export const NavbarUser: React.FC = () => {
  const loggedUser: User = JSON.parse(localStorage.getItem('user') || '{}');

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const classes = useStyles();

  const handleLogout = () => {
    localStorage.clear();
    window.location.reload();
  };

  const handleOpenMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClickAway = () => {
    setAnchorEl(null);
  };

  const mockMenuItems = [
    {
      label: 'Odhlášení',
      action: handleLogout,
    },
  ];

  return (
    <ClickAwayListener onClickAway={handleClickAway}>
      <div className={classes.navbarUser}>
        <AccountCircleIcon />
        <span>{`${loggedUser.firstName} ${loggedUser.surName}`}</span>

        <IconButton onClick={handleOpenMenu}>
          <MoreVertIcon />
        </IconButton>

        <Menu
          id="user-menu"
          open={open}
          anchorEl={anchorEl}
          PaperProps={{
            style: {
              width: 150,
              marginTop: 45,
              marginLeft: -52,
            },
          }}
        >
          {mockMenuItems.map(({ label, action }) => (
            <MenuItem key={label} onClick={action}>
              {label}
            </MenuItem>
          ))}
        </Menu>
      </div>
    </ClickAwayListener>
  );
};
