import React, { useState } from "react";
import { IconButton, Menu, MenuItem, Typography, ListItemIcon } from "@mui/material";
import AccountCircle from "@mui/icons-material/AccountCircle";
import ExitToAppIcon from "@mui/icons-material/ExitToApp";
import AccountBoxIcon from "@mui/icons-material/AccountBox";
import SettingsIcon from "@mui/icons-material/Settings";
import { useNavigate } from "react-router-dom";
import { useTuitioClient } from "@flare/tuitio-client-react";
import { blip } from "../../utils";
import { useTranslation } from "react-i18next";

const ProfileButton = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();

  const { logout } = useTuitioClient({
    onLogoutFailed: errorMessage => blip.error(errorMessage),
    onLogoutError: err => blip.error(err.message)
  });

  const [anchorEl, setAnchorEl] = useState(null);
  const openUserMenu = Boolean(anchorEl);

  const handleMenu = event => {
    setAnchorEl(event.currentTarget);
  };

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

  return (
    <div>
      <IconButton
        aria-label="account of current user"
        aria-controls="menu-appbar"
        aria-haspopup="true"
        onClick={handleMenu}
        color="inherit"
      >
        <AccountCircle />
      </IconButton>
      <Menu
        id="menu-appbar"
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: "top",
          horizontal: "right"
        }}
        keepMounted
        transformOrigin={{
          vertical: "top",
          horizontal: "right"
        }}
        open={openUserMenu}
        onClose={handleClose}
      >
        <MenuItem
          onClick={() => {
            navigate("/user-profile");
            handleClose();
          }}
        >
          <ListItemIcon sx={{ minWidth: "26px" }}>
            <AccountBoxIcon fontSize="small" />
          </ListItemIcon>
          <Typography variant="inherit">{t("User.Profile.Label")}</Typography>
        </MenuItem>
        <MenuItem
          onClick={() => {
            navigate("/settings");
            handleClose();
          }}
        >
          <ListItemIcon sx={{ minWidth: "26px" }}>
            <SettingsIcon fontSize="small" />
          </ListItemIcon>
          <Typography variant="inherit">{t("User.Settings")}</Typography>
        </MenuItem>
        <MenuItem onClick={logout}>
          <ListItemIcon sx={{ minWidth: "26px" }}>
            <ExitToAppIcon fontSize="small" />
          </ListItemIcon>
          <Typography variant="inherit">{t("User.Logout")}</Typography>
        </MenuItem>
      </Menu>
    </div>
  );
};

export default ProfileButton;
