import React, { useMemo, useState } from 'react';
import isNull from 'lodash/isNull';

import { cx } from '@leafygreen-ui/emotion';
import { usePoller, useViewportSize } from '@leafygreen-ui/hooks';
// @ts-expect-error
import ActivityFeedIcon from '@leafygreen-ui/icon/dist/ActivityFeed';
// @ts-expect-error
import BellIcon from '@leafygreen-ui/icon/dist/Bell';
// @ts-expect-error
import InviteUserIcon from '@leafygreen-ui/icon/dist/InviteUser';
// @ts-expect-error
import VerticalEllipsisIcon from '@leafygreen-ui/icon/dist/VerticalEllipsis';
import IconButton from '@leafygreen-ui/icon-button';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import { Menu, MenuItem } from '@leafygreen-ui/menu';
import Tooltip from '@leafygreen-ui/tooltip';

import { breakpoints } from '../breakpoints';
import { ProjectSelect } from '../mongo-select';
import { useMongoNavContext } from '../MongoNavContext';
import { useOnElementClick } from '../on-element-click-provider';
import {
  navContainerBaseStyle,
  navContainerThemeStyle,
  navSectionStyle,
} from '../styles';
import {
  ActiveNavElement,
  Environment,
  Mode,
  NavElement,
  ProjectStatus,
} from '../types';

import { ProductTabs } from './ProductTabs';
import { ProjectStatusBadge } from './project-nav-helpers';
import {
  alertBadgeStyle,
  iconButtonThemeStyles,
  menuIconButtonStyle,
  projectNavContainerBaseStyle,
  projectNavContainerThemeStyle,
  projectNavFirstSectionStyle,
  projectSelectWrapperstyle,
  tooltipStyles,
} from './ProjectNav.styles';
import { ProjectNavProps } from './ProjectNav.types';

const {
  ProjectNavProjectDropdown,
  ProjectNavProjectSettings,
  ProjectNavProjectSupport,
  ProjectNavProjectIntegrations,
  ProjectNavInvite,
  ProjectNavActivityFeed,
  ProjectNavAlerts,
} = NavElement;

export default function ProjectNav({
  /* eslint-disable react/prop-types */
  admin,
  data,
  constructProjectURL,
  urls,
  onProjectChange,
  hosts,
  mode,
  alertPollingInterval,
  environment = Environment.Commercial,
}: /* eslint-enable react/prop-types */
ProjectNavProps) {
  const [open, setOpen] = useState(false);
  const { theme } = useDarkMode();
  const {
    activeNav,
    isLoading,
    currentProject: current,
  } = useMongoNavContext();
  const [alerts, setAlerts] = useState(current?.alertsOpen ?? 0);
  const onElementClick = useOnElementClick();
  const viewportSize = useViewportSize();

  const isDisabled = isLoading || isNull(current);

  function fetchAlertsCount() {
    return fetch(
      `${hosts.cloud}/user/shared/alerts/project/${currentProjectId}`,
      {
        credentials: 'include',
        mode: 'cors',
        method: 'GET',
      },
    )
      .then(response => response.json())
      .then(result => setAlerts(result.length))
      .catch(console.error);
  }

  const currentProjectId = current?.projectId;

  usePoller(fetchAlertsCount, {
    interval: alertPollingInterval,
    enabled: mode === Mode.Production && currentProjectId != null,
  });

  const isMobile = viewportSize
    ? viewportSize.width < breakpoints.small
    : false;

  const isProjectInvite =
    !isDisabled && activeNav === ActiveNavElement.ProjectNavInvite;
  const isActivityFeed =
    !isDisabled && activeNav === ActiveNavElement.ProjectNavActivityFeed;
  const isProjectAlerts =
    !isDisabled && activeNav === ActiveNavElement.ProjectNavAlerts;

  const sharedTooltipOnClick: React.MouseEventHandler = e => e.preventDefault();

  const sharedTooltipProps = useMemo(() => {
    return {
      variant: 'dark',
      usePortal: false,
      className: tooltipStyles,
      onClick: sharedTooltipOnClick,
    };
  }, []);

  return (
    <nav
      className={cx(
        navContainerBaseStyle,
        navContainerThemeStyle[theme],
        projectNavContainerBaseStyle,
        projectNavContainerThemeStyle[theme],
      )}
      aria-label="project navigation"
      data-testid="project-nav"
    >
      <div className={cx(navSectionStyle, projectNavFirstSectionStyle)}>
        <div className={projectSelectWrapperstyle}>
          <ProjectSelect
            current={current}
            data={data}
            constructProjectURL={constructProjectURL}
            hosts={hosts}
            mode={mode}
            urls={urls.mongoSelect}
            admin={admin}
            onChange={onProjectChange}
          />

          <Menu
            open={open}
            setOpen={setOpen}
            usePortal={false}
            trigger={
              <IconButton
                aria-label="More"
                className={menuIconButtonStyle}
                active={open}
                disabled={isDisabled}
                data-testid="project-nav-project-menu"
                onClick={onElementClick(ProjectNavProjectDropdown)}
                aria-expanded={open}
              >
                <VerticalEllipsisIcon />
              </IconButton>
            }
          >
            <MenuItem
              href={urls.projectNav.settings!}
              data-testid="project-nav-settings"
              active={activeNav === ActiveNavElement.ProjectNavProjectSettings}
              onClick={onElementClick(ProjectNavProjectSettings, () =>
                setOpen(false),
              )}
            >
              Project Settings
            </MenuItem>

            <MenuItem
              href={urls.projectNav.support!}
              data-testid="project-nav-support"
              active={activeNav === ActiveNavElement.ProjectNavProjectSupport}
              onClick={onElementClick(ProjectNavProjectSupport, () =>
                setOpen(false),
              )}
            >
              Project Support
            </MenuItem>
            <MenuItem
              href={urls.projectNav.integrations!}
              data-testid="project-nav-integrations"
              active={
                activeNav === ActiveNavElement.ProjectNavProjectIntegrations
              }
              onClick={onElementClick(ProjectNavProjectIntegrations, () =>
                setOpen(false),
              )}
            >
              Integrations
            </MenuItem>
          </Menu>
        </div>

        {!isMobile &&
          admin &&
          current?.status &&
          Object.values(ProjectStatus).includes(current?.status) && (
            <ProjectStatusBadge
              currentStatus={current.status}
              displayName={current.statusDisplayName}
            />
          )}

        <ProductTabs
          environment={environment}
          hosts={hosts}
          urls={urls.projectNav}
        />
      </div>

      {!isMobile && (
        <div className={navSectionStyle}>
          <Tooltip
            {...sharedTooltipProps}
            tabIndex={-1}
            align="bottom"
            justify="middle"
            usePortal={false}
            trigger={
              <IconButton
                aria-label={`Invite to Project: ${current?.projectName}`}
                href={urls.projectNav.invite as string}
                className={cx({
                  [iconButtonThemeStyles[theme]]: isProjectInvite,
                })}
                size="large"
                disabled={isDisabled}
                active={isProjectInvite}
                data-testid="project-nav-invite"
                onClick={onElementClick(ProjectNavInvite)}
              >
                <InviteUserIcon size="large" />
              </IconButton>
            }
          >
            Invite To Project
          </Tooltip>

          <Tooltip
            {...sharedTooltipProps}
            align="bottom"
            justify="middle"
            usePortal={false}
            trigger={
              <IconButton
                aria-label="Project Activity Feed"
                href={urls.projectNav.activityFeed as string}
                size="large"
                className={cx({
                  [iconButtonThemeStyles[theme]]: isActivityFeed,
                })}
                disabled={isDisabled}
                active={isActivityFeed}
                data-testid="project-nav-activity-feed"
                onClick={onElementClick(ProjectNavActivityFeed)}
              >
                <ActivityFeedIcon size="large" />
              </IconButton>
            }
          >
            View the Project Activity Feed
          </Tooltip>

          <Tooltip
            {...sharedTooltipProps}
            align="bottom"
            justify="end"
            usePortal={false}
            trigger={
              <IconButton
                aria-label={`Alerts for Project: ${current?.projectName}`}
                href={urls.projectNav.alerts as string}
                size="large"
                disabled={isDisabled}
                active={isProjectAlerts}
                data-testid="project-nav-alerts"
                onClick={onElementClick(ProjectNavAlerts)}
                className={cx({
                  [iconButtonThemeStyles[theme]]: isProjectAlerts,
                })}
              >
                {alerts > 0 && (
                  <div
                    className={alertBadgeStyle}
                    data-testid="project-nav-alerts-badge"
                  >
                    {alerts}
                  </div>
                )}

                <BellIcon size="large" />
              </IconButton>
            }
          >
            View the Project Alerts
          </Tooltip>
        </div>
      )}
    </nav>
  );
}
