import {
  IconButton,
  ListItemIcon,
  ListItemText,
  Menu,
  MenuItem,
  Tooltip
} from "@mui/material";
import RemoveSelfIcon from "@mui/icons-material/ExitToApp";
import MoreIcon from "@mui/icons-material/MoreVert";
import GroupSettingsIcon from "@mui/icons-material/Settings";
import ShareObjectIcon from "@mui/icons-material/Share";
import ObjectUsersIcon from "@mui/icons-material/AccountCircle";
import { Team, teamScope } from "models";
import { pond } from "protobuf-ts/pond";
import React, { useState } from "react";
import ObjectUsers from "user/ObjectUsers";
import RemoveSelfFromObject from "user/RemoveSelfFromObject";
import ShareObject from "user/ShareObject";
import { isOffline } from "utils/environment";
import TeamSettings from "./TeamSettings";
import NotificationButton from "common/NotificationButton";
import { blue } from "@mui/material/colors";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles(() => ({
  shareIcon: {
    color: blue["500"],
    "&:hover": {
      color: blue["600"]
    }
  },
  removeIcon: {
    color: "var(--status-alert)"
  },
  red: {
    color: "var(--status-alert)"
  }
}));

interface Props {
  team: Team;
  permissions: pond.Permission[];
  refreshCallback: () => void;
  preferences: pond.TeamPreferences;
  toggleNotificationPreference: () => void;
  removeSelfCallback?: () => void; 
}

interface OpenState {
  share: boolean;
  users: boolean;
  teams: boolean;
  settings: boolean;
  removeSelf: boolean;
}

export default function TeamActions(props: Props) {
  const classes = useStyles();
  const { team, permissions, refreshCallback, preferences, toggleNotificationPreference } = props;
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const [openState, setOpenState] = useState<OpenState>({
    share: false,
    users: false,
    teams: false,
    settings: false,
    removeSelf: false
  });

  const groupMenu = () => {
    const canShare = permissions.includes(pond.Permission.PERMISSION_SHARE);
    const canManageUsers = permissions.includes(pond.Permission.PERMISSION_USERS);
    return (
      <Menu
        id="groupMenu"
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={() => setAnchorEl(null)}
        keepMounted
        disableAutoFocusItem>
        {!isOffline() && canShare && (
          <MenuItem
            dense
            onClick={() => {
              setOpenState({ ...openState, share: true });
              setAnchorEl(null);
            }}
            // button
            >
            <ListItemIcon>
              <ShareObjectIcon className={classes.shareIcon} />
            </ListItemIcon>
            <ListItemText primary="Share" />
          </MenuItem>
        )}
        {!isOffline() && canManageUsers && (
          <MenuItem
            dense
            onClick={() => {
              setOpenState({ ...openState, users: true });
              setAnchorEl(null);
            }}
            // button
            >
            <ListItemIcon>
              <ObjectUsersIcon />
            </ListItemIcon>
            <ListItemText primary="Users" />
          </MenuItem>
        )}
        <MenuItem
          dense
          onClick={() => {
            setOpenState({ ...openState, removeSelf: true });
            setAnchorEl(null);
          }}
          // button
          >
          <ListItemIcon>
            <RemoveSelfIcon className={classes.red} />
          </ListItemIcon>
          <ListItemText primary="Leave" />
        </MenuItem>
      </Menu>
    );
  };

  const dialogs = () => {
    const key = team.key();
    const label = team.name();
    return (
      <React.Fragment>
        <TeamSettings
          team={team}
          permissions={permissions}
          teamDialogOpen={openState.settings}
          closeTeamDialogCallback={() => {
            setOpenState({ ...openState, settings: false });
          }}
          refreshCallback={refreshCallback}
        />
        <ShareObject
          scope={teamScope(key)}
          label={label}
          permissions={permissions}
          isDialogOpen={openState.share}
          closeDialogCallback={() => setOpenState({ ...openState, share: false })}
        />
        <ObjectUsers
          scope={teamScope(key)}
          label={label}
          permissions={permissions}
          isDialogOpen={openState.users}
          closeDialogCallback={() => setOpenState({ ...openState, users: false })}
          refreshCallback={refreshCallback}
        />
        <RemoveSelfFromObject
          scope={teamScope(key)}
          label={label}
          isDialogOpen={openState.removeSelf}
          closeDialogCallback={(removeSelf: boolean) => {
            // console.log(removeSelf)
            if (removeSelf) refreshCallback()
            setOpenState({ ...openState, removeSelf: false })
          }}
        />
      </React.Fragment>
    );
  };

  const canWrite = permissions.includes(pond.Permission.PERMISSION_WRITE);
  return (
    <React.Fragment>
      <NotificationButton
        notify={preferences.notify}
        onChange={toggleNotificationPreference}
        tooltip={
          "Notifications for " +
          team.name() +
          " are " +
          (preferences.notify ? "enabled" : "disabled")
        }
        // hidden={isLoading}
      />
      {canWrite && (
        <Tooltip title="Team Settings">
          <IconButton onClick={() => setOpenState({ ...openState, settings: true })}>
            <GroupSettingsIcon />
          </IconButton>
        </Tooltip>
      )}
      <IconButton
        aria-owns={anchorEl ? "groupMenu" : undefined}
        aria-haspopup="true"
        onClick={(event: React.MouseEvent<HTMLButtonElement>) => setAnchorEl(event.currentTarget)}>
        <MoreIcon />
      </IconButton>
      {groupMenu()}
      {dialogs()}
    </React.Fragment>
  );
}
