import React from 'react';

import { Menu, MenuItem } from '@leafygreen-ui/menu';

import { useMongoNavContext } from '../../MongoNavContext';
import { useOnElementClick } from '../../on-element-click-provider';
import { ActiveNavElement, NavElement } from '../../types';

type PolyProps = { as: 'a'; href: string } | { as: 'button' };

interface AccessManagerMenuProps {
  refEl: React.RefObject<HTMLElement>;
  open: boolean;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
  // TODO: read currentOrg & currentProject from Context
  orgHref?: string;
  orgName?: string;
  projectHref?: string;
  projectName?: string;
  displayProjectAccess: boolean;
}

export const AccessManagerMenu = ({
  refEl,
  open,
  setOpen,
  orgHref,
  orgName,
  projectHref,
  projectName,
  displayProjectAccess,
}: AccessManagerMenuProps) => {
  const onElementClick = useOnElementClick();
  const { activeNav } = useMongoNavContext();

  const orgAccessManagerProps: PolyProps = orgHref
    ? { as: 'a', href: orgHref }
    : { as: 'button' };

  const projectManagerProps: PolyProps =
    projectName && projectHref
      ? { as: 'a', href: projectHref }
      : { as: 'button' };

  return (
    <Menu
      maxHeight={256}
      open={open}
      setOpen={setOpen}
      usePortal={false}
      popoverZIndex={1}
      refEl={refEl}
    >
      <MenuItem
        {...orgAccessManagerProps}
        data-testid="org-nav-dropdown-org-access-manager"
        description={orgName}
        size="large"
        active={activeNav === ActiveNavElement.OrgNavDropdownOrgAccessManager}
        onClick={onElementClick(NavElement.OrgNavDropdownOrgAccessManager, () =>
          setOpen(false),
        )}
      >
        Organization Access
      </MenuItem>

      <MenuItem
        {...projectManagerProps}
        data-testid="org-nav-dropdown-project-access-manager"
        size="large"
        active={
          activeNav === ActiveNavElement.OrgNavDropdownProjectAccessManager
        }
        disabled={!displayProjectAccess}
        description={displayProjectAccess ? projectName : 'None'}
        onClick={onElementClick(
          NavElement.OrgNavDropdownProjectAccessManager,
          () => setOpen(false),
        )}
      >
        Project Access
      </MenuItem>
    </Menu>
  );
};
