import React from "react";
import { IconButton, MenuItem } from "@material-ui/core";
import Menu from "@material-ui/core/Menu";
import EditIcon from "@material-ui/icons/Edit";
import { UPPERCASE_USER_ROLES, UppercaseUserRole } from "../jwt/jwt";
import { useMutation } from "@apollo/client";
import {
  CHANGE_ROLE,
  ChangeRoleResponse,
  ChangeRoleVariables,
} from "../backend/mutations/userRole";
import { useSnackbar } from "notistack";
import { GET_PERSONS_SORTED_BY_ROLE } from "../backend/queries/person";

interface ChangeRoleMenuProps {
  currentRole: UppercaseUserRole;
  currentUserRowId: number;
  disabled?: boolean;
}

export default function ChangeRoleMenu(
  props: ChangeRoleMenuProps
): React.ReactElement {
  const { enqueueSnackbar } = useSnackbar();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const otherRoles = UPPERCASE_USER_ROLES.filter(
    (role) => role != props.currentRole
  );
  const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const [changeRole] = useMutation<ChangeRoleResponse, ChangeRoleVariables>(
    CHANGE_ROLE,
    {
      onCompleted() {
        handleClose();
      },
      onError(e) {
        console.error(e);
        handleClose();
        enqueueSnackbar("Ein Fehler ist aufgetreten, versuche es erneut.", {
          variant: "error",
        });
      },
      refetchQueries: [{ query: GET_PERSONS_SORTED_BY_ROLE }],
    }
  );
  const displayRole = (role: UppercaseUserRole) => {
    switch (role) {
      case "KANDIMAT_CANDIDATE":
        return "zu Kandidat:in machen";
      case "KANDIMAT_EDITOR":
        return "zu RedakteurIn machen";
      case "KANDIMAT_PERSON":
        return "zu Standard User machen";
    }
  };
  return (
    <React.Fragment>
      <IconButton
        aria-label="role of current user"
        aria-controls="change-role"
        aria-haspopup="true"
        onClick={handleMenu}
        color="inherit"
        disabled={props.disabled}
      >
        <EditIcon />
      </IconButton>
      <Menu
        id="change-role"
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        keepMounted
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        open={open}
        onClose={handleClose}
      >
        {otherRoles.map((role) => (
          <MenuItem
            key={role}
            onClick={() => {
              changeRole({
                variables: {
                  personRowId: props.currentUserRowId,
                  newRole: role,
                },
              });
            }}
          >
            {displayRole(role)}
          </MenuItem>
        ))}
      </Menu>
    </React.Fragment>
  );
}
