import { UniDriver } from '@wix/wix-ui-test-utils/unidriver';
import { PopoverMenuUniDriver } from '@wix/design-system/dist/testkit/unidriver';
import { PopoverMenuUniDriver as PopoverMenuUniDriverFactory } from '@wix/design-system/dist/types/PopoverMenu/PopoverMenu.uni.driver';
import { UniDriverFactory } from '../uniDriverFactory';

export function EditableColumnHeaderUniDriver(
  base: UniDriver,
  body: UniDriver,
) {
  const moreButton = base.$('[data-hook$="-more-button"]');

  const getPopoverMenu = async () => {
    const dataHook = await base.attr('data-hook');
    return (
      PopoverMenuUniDriver as UniDriverFactory<PopoverMenuUniDriverFactory>
    )(body.$(`[data-hook="${dataHook}-menu"]`), body);
  };

  return {
    exists: () => moreButton.exists(),

    /** Whether the "..." more button exists */
    hasMoreButton: () => moreButton.exists(),

    /** Hover the column header (reveals the "..." button in designs that hide it) */
    hover: () => base.hover(),

    /** Click the "..." button to open the popover menu */
    clickMoreButton: () => moreButton.click(),

    /** Whether the popover menu is currently open */
    isMenuOpen: async () => (await getPopoverMenu()).isMenuOpen(),

    /** Number of items in the popover menu */
    menuItemCount: async () => (await getPopoverMenu()).childrenCount(),

    /** Get the text content of a menu item by index */
    getMenuItemText: async (index: number) =>
      (await getPopoverMenu()).itemContentAt(index),

    /** Click a menu item by index */
    clickMenuItem: async (index: number) =>
      (await getPopoverMenu()).clickAtChild(index),

    /** Whether the menu item at the given index is disabled */
    isMenuItemDisabled: async (index: number) => {
      const popover = await getPopoverMenu();
      const contentElement = await popover.getContentElement();
      const item = contentElement
        .$$('[data-hook="dropdown-layout-options"] > *')
        .get(index);
      return (await item.attr('data-option-disabled')) === 'true';
    },
  };
}
