import React from 'react';
import { PopoverMenu, IconButton, Tooltip } from '@wix/design-system';
import { MoreSmall } from '@wix/wix-ui-icons-common';
import { usePageContext, useWixPatternsContainer } from '@wix/bex-core/react';
import type { FieldActionsMenuConfig } from './headerActionTypes';
import { actionMenuItems } from './actionMenuItems';

export function FieldActionsPopover({
  actions,
  buttonDataHook,
  menuDataHook,
  tooltipContent,
  onShow,
  disabledTooltip,
}: FieldActionsMenuConfig) {
  const { translate: t } = useWixPatternsContainer();
  const { stackingRootRef } = usePageContext();
  const tooltip = tooltipContent ?? t('cairo.moreActions');
  const menuItems = actionMenuItems(actions);

  if (menuItems.length === 0) {
    if (!disabledTooltip) {
      return null;
    }
    return (
      <Tooltip
        dataHook={
          buttonDataHook ? `${buttonDataHook}-disabled-tooltip` : undefined
        }
        content={disabledTooltip}
      >
        <IconButton
          size="tiny"
          disabled
          ariaLabel={t('cairo.moreActions')}
          dataHook={buttonDataHook}
        >
          <MoreSmall />
        </IconButton>
      </Tooltip>
    );
  }

  return (
    <PopoverMenu
      textSize="small"
      placement="bottom-end"
      appendTo={stackingRootRef.current || 'parent'}
      dataHook={menuDataHook}
      onShow={onShow}
      triggerElement={
        <Tooltip content={tooltip}>
          <IconButton
            size="tiny"
            skin="light"
            ariaLabel={t('cairo.moreActions')}
            dataHook={buttonDataHook}
          >
            <MoreSmall />
          </IconButton>
        </Tooltip>
      }
    >
      {menuItems}
    </PopoverMenu>
  );
}
