import React, { useRef, useState } from 'react';
import { cx } from '@leafygreen-ui/emotion';
// @ts-expect-error
import CaretDownIcon from '@leafygreen-ui/icon/dist/CaretDown';
import { isNull } from 'lodash';
import { useMongoNavContext } from '../../MongoNavContext';
import { useOnElementClick } from '../../on-element-click-provider';
import { ActiveNavElement, NavElement } from '../../types';
import {
  caretBaseStyle,
  caretClassName,
  caretOpenThemeStyle,
  caretThemeStyle,
  openOrgMenuThemeStyle,
  orgNavLinkWrapperClassName,
} from '../OrgNav.styles';
import { OrgNavLink } from './OrgNavLink';
import { AccessManagerMenu } from './AccessManagerMenu';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import { OrgNavProps } from '../OrgNav';

interface AccessManagerControlProps
  extends Pick<OrgNavProps, 'onPremEnabled' | 'urls' | 'showProjectNav'> {}

export const AccessManagerControl = ({
  onPremEnabled,
  urls,
  showProjectNav,
}: AccessManagerControlProps) => {
  const onElementClick = useOnElementClick();
  const {
    isLoading,
    activeNav,
    currentProject,
    currentOrg: current,
    showUnifiedAccessManagementNav,
  } = useMongoNavContext();
  const { theme } = useDarkMode();
  const [accessManagerOpen, setAccessManagerOpen] = useState(false);
  const accessMgrLinkRef = useRef<HTMLAnchorElement | HTMLButtonElement>(null);

  const displayProjectAccess = onPremEnabled
    ? !!currentProject?.projectId
    : showProjectNav;

  return (
    <OrgNavLink
      isButton
      href={
        showUnifiedAccessManagementNav ? urls.orgNav.accessManager : undefined
      }
      isActive={(
        [
          ActiveNavElement.OrgNavAccessManagerDropdown,
          ActiveNavElement.OrgNavDropdownOrgAccessManager,
          ActiveNavElement.OrgNavDropdownProjectAccessManager,
        ] as Array<ActiveNavElement | undefined>
      ).includes(activeNav)}
      loading={isLoading}
      data-testid="org-nav-access-manager-dropdown"
      onClick={onElementClick(NavElement.OrgNavAccessManagerDropdown, () => {
        if (!showUnifiedAccessManagementNav) {
          setAccessManagerOpen(curr => !curr);
        }
      })}
      aria-expanded={accessManagerOpen}
      ref={accessMgrLinkRef}
      disabled={isNull(current)}
      className={cx({
        [openOrgMenuThemeStyle[theme]]: accessManagerOpen,
      })}
    >
      <span className={orgNavLinkWrapperClassName}>
        Access Manager
        {!showUnifiedAccessManagementNav && (
          <CaretDownIcon
            className={cx(
              caretClassName,
              caretBaseStyle,
              caretThemeStyle[theme],
              {
                [caretOpenThemeStyle[theme]]: accessManagerOpen,
              },
            )}
          />
        )}
      </span>
      {current && (
        <AccessManagerMenu
          refEl={accessMgrLinkRef}
          open={accessManagerOpen}
          setOpen={setAccessManagerOpen}
          orgHref={urls.orgNav.accessManager}
          orgName={current.orgName}
          projectHref={urls.projectNav.accessManager}
          projectName={currentProject?.projectName}
          displayProjectAccess={displayProjectAccess}
        />
      )}
    </OrgNavLink>
  );
};
