import type { UniDriver } from '@wix/wix-ui-test-utils/unidriver';
import {
  ButtonUniDriver,
  ListItemActionUniDriver,
  MessageModalLayoutUniDriver,
  TableActionCellUniDriver,
} from '@wix/design-system/dist/testkit/unidriver';

export const CollectionItemActionsUniDriver = (
  base: UniDriver,
  body: UniDriver,
) => {
  const actionCell = TableActionCellUniDriver(
    base.$('[data-hook="collection-action-cell"]'),
    body,
  );

  const getActionModal = () =>
    MessageModalLayoutUniDriver(
      body.$('[data-hook="collection-action-modal"]'),
      body,
    );

  const getPopoverMenuContent = async () => {
    const popoverMenu = await actionCell.getHiddenActionsPopoverMenuDriver();
    return popoverMenu.getContentElement();
  };

  const isSecondaryHiddenAction = async (dataHook: string) => {
    const popover = await actionCell.getHiddenActionsPopoverMenuDriver();

    if (await popover.exists()) {
      await actionCell.clickPopoverMenu();
      const popoverMenuContent = await getPopoverMenuContent();
      return popoverMenuContent.$(`[data-hook="${dataHook}"]`).exists();
    }

    return false;
  };

  const getHiddenActionBase = async (dataHook: string) => {
    const popoverMenuContent = await getPopoverMenuContent();
    return popoverMenuContent.$(`[data-hook="${dataHook}"]`);
  };

  const getVisibleActionBase = async (dataHook: string) => {
    return base
      .$(`[data-hook="${dataHook}"]`)
      .$('[data-hook="table-action-cell-visible-action"]');
  };

  const clickAction = async (dataHook: string) => {
    const isHidden = await isSecondaryHiddenAction(dataHook);

    if (isHidden) {
      await actionCell.clickHiddenActionByDataHook(dataHook);
    } else {
      await base
        .$(`[data-hook="${dataHook}"]`)
        .$('[data-hook="table-action-cell-visible-action"]')
        .click();
    }
  };

  const clickSecondaryAction = async (dataHook: string) => {
    await actionCell.clickPopoverMenu();
    await actionCell.clickHiddenActionByDataHook(dataHook);
  };

  const confirmActionModal = async () => {
    const modal = getActionModal();
    const confirmButton = await modal.getPrimaryButtonDriver();
    await confirmButton.click();
  };

  const isSecondaryActionDisabled = async (dataHook: string) =>
    (
      await ListItemActionUniDriver(await getHiddenActionBase(dataHook), body)
    ).isDisabled();

  const getSecondaryActionTitleText = async (dataHook: string) =>
    (
      await ListItemActionUniDriver(await getHiddenActionBase(dataHook), body)
    ).getTitleText();

  const isVisibleSecondaryActionDisabled = async (dataHook: string) =>
    (
      await ButtonUniDriver(await getVisibleActionBase(dataHook), body)
    ).isButtonDisabled();

  return {
    ...actionCell,
    clickSecondaryAction,
    clickAction,
    getActionModal,
    confirmActionModal,
    isSecondaryActionDisabled,
    getSecondaryActionTitleText,
    isVisibleSecondaryActionDisabled,
  };
};
