import React, { useCallback } from 'react';
import kebabCase from 'lodash/kebabCase';

import { cx } from '@leafygreen-ui/emotion';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import Tooltip from '@leafygreen-ui/tooltip';

import { useMongoNavContext } from '../../MongoNavContext';
import { useOnElementClick } from '../../on-element-click-provider';
import {
  CurrentProjectInterface,
  Environment,
  NavElement,
  PlanType,
  Product,
  ProductName,
  URLS,
} from '../../types';
import { ProjectNavProps } from '../ProjectNav.types';

import {
  AtlasBlob,
  ChartsBlob,
  CloudManagerBlob,
  RealmBlob,
} from './ProductBlobs';
import {
  blobClassName,
  blobStyle,
  productTabBaseStyle,
  productTabsWrapperStyle,
  productTabThemeStyle,
  tabActiveBaseStyle,
  tabActiveThemeStyle,
  tabContentClassName,
  tabDisabledFocusThemeStyle,
  tabDisabledThemeStyle,
  tabFocusBaseStyle,
  tabFocusThemeStyle,
  tabNameStyle,
} from './styles';

const { ProjectNavCloud, ProjectNavRealm, ProjectNavCharts } = NavElement;

const BlobMap: Record<ProductName, React.ExoticComponent<any>> = {
  'Cloud Manager': CloudManagerBlob,
  'App Services': RealmBlob,
  'Data Services': AtlasBlob,
  Realm: RealmBlob,
  Charts: ChartsBlob,
};

interface ProductTabProps {
  id: Product;
  name: ProductName;
  href: string;
  NavElement: NavElement;
  current?: CurrentProjectInterface;
  activeProduct?: Product;
}

function ProductTab({
  id,
  name,
  href: hrefProp,
  current,
  NavElement,
  activeProduct,
}: ProductTabProps) {
  const { theme } = useDarkMode();
  const onElementClick = useOnElementClick();
  const Blob = BlobMap[name];
  const productKebab = kebabCase(name);

  const useCNRegionsOnly =
    current?.useCNRegionsOnly === true && current?.planType === PlanType.Atlas;

  const isCNRegionsOnly = useCallback(
    (product: Product) => {
      const disabledProducts: Array<Product> = [Product.Realm, Product.Charts];
      return useCNRegionsOnly && disabledProducts.includes(product);
    },
    [useCNRegionsOnly],
  );

  const disabled = isCNRegionsOnly(id) || !current;
  const href = id === 'cloud' || !disabled ? hrefProp : undefined;

  const Tab = (
    <a
      aria-disabled={disabled}
      href={href}
      tabIndex={0} // Keep tabindex even when there's no href
      onClick={onElementClick(NavElement)}
      className={cx(
        productTabBaseStyle,
        productTabThemeStyle[theme],
        tabFocusBaseStyle,
        tabFocusThemeStyle[theme],
        {
          [cx(tabActiveBaseStyle, tabActiveThemeStyle[theme])]:
            current && activeProduct === id,
          [cx(tabDisabledThemeStyle[theme], tabDisabledFocusThemeStyle[theme])]:
            disabled,
        },
      )}
    >
      <Blob className={cx(blobClassName, blobStyle)} />
      <span
        data-testid={`project-nav-${productKebab}`}
        data-product={name}
        className={cx(tabContentClassName, tabNameStyle)}
      >
        {name}
      </span>
    </a>
  );

  return (
    <Tooltip
      data-testid={`project-nav-tooltip-${productKebab}`}
      trigger={Tab}
      enabled={isCNRegionsOnly(id)}
      usePortal={false}
    >
      This product is not available for AWS China regions-only projects
    </Tooltip>
  );
}

interface ProductTabsProps {
  environment?: ProjectNavProps['environment'];
  hosts: ProjectNavProps['hosts'];
  urls: URLS['projectNav'];
}
export const ProductTabs = ({ environment, hosts, urls }: ProductTabsProps) => {
  const { useAppServicesBranding, activeProduct, currentProject } =
    useMongoNavContext();
  const isCloudManager = currentProject?.planType === PlanType.Cloud;
  const isGovernment = environment === Environment.Government;

  const cloudHref = currentProject
    ? `${hosts.cloud}/v2/${currentProject?.projectId}#`
    : hosts.cloud;

  return (
    <div aria-label="Product Tabs" className={cx(productTabsWrapperStyle)}>
      <ProductTab
        id="cloud"
        name={isCloudManager ? 'Cloud Manager' : 'Data Services'}
        href={cloudHref}
        NavElement={ProjectNavCloud}
        current={currentProject}
        activeProduct={activeProduct}
      />

      {!isGovernment && !isCloudManager && (
        <>
          <ProductTab
            id="realm"
            name={useAppServicesBranding ? 'App Services' : 'Realm'}
            href={urls.realm ?? hosts.realm}
            NavElement={ProjectNavRealm}
            current={currentProject}
            activeProduct={activeProduct}
          />
          <ProductTab
            id="charts"
            name="Charts"
            href={urls.charts ?? hosts.charts}
            NavElement={ProjectNavCharts}
            current={currentProject}
            activeProduct={activeProduct}
          />
        </>
      )}
    </div>
  );
};
