import React, { useState, useCallback, useRef } from 'react';
import { PopoverMenu, IconButton, Tooltip } from '@wix/design-system';
import { MoreSmall } from '@wix/wix-ui-icons-common';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import type { HeaderAction } from './headerActionTypes';
import { actionMenuItems } from './actionMenuItems';
import { useCloseOnAncestorScroll } from '../../hooks/useCloseOnAncestorScroll';

export interface HeaderActionsPopoverProps {
  actions: HeaderAction[][];
  dataHook?: string;
  className?: string;
}

export function HeaderActionsPopover({
  actions,
  dataHook,
  className,
}: HeaderActionsPopoverProps) {
  const { translate: t } = useWixPatternsContainer();
  const [menuOpen, setMenuOpen] = useState(false);
  const [popoverKey, setPopoverKey] = useState(0);
  const wrapperRef = useRef<HTMLDivElement>(null);

  const closePopover = useCallback(() => {
    setMenuOpen(false);
    setPopoverKey((k) => k + 1);
  }, []);

  useCloseOnAncestorScroll(wrapperRef, closePopover, menuOpen);

  const menuItems = actionMenuItems(actions);
  if (menuItems.length === 0) {
    return null;
  }

  return (
    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
    <div
      ref={wrapperRef}
      className={className}
      data-menu-open={menuOpen ? 'true' : 'false'}
      data-hook={dataHook}
      onClick={(e) => e.stopPropagation()}
    >
      <Tooltip
        content={t('cairo.moreActions')}
        disabled={menuOpen}
        appendTo="window"
      >
        <PopoverMenu
          key={popoverKey}
          dataHook={dataHook ? `${dataHook}-menu` : undefined}
          textSize="small"
          triggerElement={
            <IconButton
              size="tiny"
              skin="dark"
              priority="tertiary"
              ariaLabel={t('cairo.moreActions')}
              dataHook={dataHook ? `${dataHook}-more-button` : undefined}
            >
              <MoreSmall />
            </IconButton>
          }
          appendTo="window"
          placement="bottom-end"
          onShow={() => setMenuOpen(true)}
          onHide={() => setMenuOpen(false)}
        >
          {menuItems}
        </PopoverMenu>
      </Tooltip>
    </div>
  );
}
