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, User } 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";
import { useGlobalState, useUserAPI } from "providers";
import { Star, StarBorder } from "@mui/icons-material";

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 [{ as, user }, dispatch] = useGlobalState()
  const userAPI = useUserAPI()

  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);
            }}
            >
            <ListItemIcon>
              <ShareObjectIcon className={classes.shareIcon} />
            </ListItemIcon>
            <ListItemText primary="Share" />
          </MenuItem>
        )}
        {!isOffline() && canManageUsers && (
          <MenuItem
            dense
            onClick={() => {
              setOpenState({ ...openState, users: true });
              setAnchorEl(null);
            }}
            >
            <ListItemIcon>
              <ObjectUsersIcon />
            </ListItemIcon>
            <ListItemText primary="Users" />
          </MenuItem>
        )}
        <MenuItem
          dense
          onClick={() => {
            setOpenState({ ...openState, removeSelf: true });
            setAnchorEl(null);
          }}
          >
          <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 })}
          useImitation={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) => {
            if (removeSelf) refreshCallback()
            setOpenState({ ...openState, removeSelf: false })
          }}
        />
      </React.Fragment>
    );
  };

  const selectFavorite = () => {
    let newUser = user.protobuf()
    if (!newUser.settings) newUser.settings = pond.UserSettings.create()
    newUser.settings.defaultTeam = user.settings.defaultTeam === team.key() ? "" : team.key();
    userAPI.updateUser(user.id(), newUser).then(() => {
      let u = User.create(newUser)
      dispatch({ key: "user", value: u });
    })
  }

  const canWrite = permissions.includes(pond.Permission.PERMISSION_WRITE);
  const canFavorite = !as.includes("auth")
  const isFavorite = user.settings.defaultTeam === team.key()
  return (
    <React.Fragment>
      { canFavorite &&
        <Tooltip title={ !isFavorite ? "Make this your default team" : "Remove default team"} >
          <IconButton onClick={selectFavorite}>
            { isFavorite ?
              <Star />
            :
              <StarBorder />
            }
          </IconButton>
        </Tooltip>
      }
      <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>
  );
}
