import React, { memo } from 'react';

import type { TooltipProps } from '@redocly/theme/core/types';

import { Tooltip as AnchorTooltip } from '@redocly/theme/components/Tooltip/AnchorTooltip';
import { Tooltip as JsTooltip } from '@redocly/theme/components/Tooltip/JsTooltip';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { getDefaultFallbackPlacements } from '@redocly/theme/core/utils';

function TooltipComponent(props: TooltipProps): React.ReactElement {
  const { useAnchorPositioning } = useThemeHooks();
  const { isSupported } = useAnchorPositioning();

  const fallbackPlacements =
    props.fallbackPlacements ?? getDefaultFallbackPlacements(props.placement ?? 'top');

  if (isSupported) {
    return (
      <AnchorTooltip
        {...props}
        fallbackPlacements={fallbackPlacements}
        arrowPosition={prepareArrowPosition(props.arrowPosition)}
      />
    );
  }
  return <JsTooltip {...props} fallbackPlacements={fallbackPlacements} />;
}

export const Tooltip = memo<TooltipProps>(TooltipComponent);

const prepareArrowPosition = (arrowPosition: TooltipProps['arrowPosition']) => {
  if (arrowPosition === 'bottom' || arrowPosition === 'top') {
    return 'center';
  }
  return arrowPosition;
};
