import { SidePanelUniDriver } from '@wix/design-system/dist/testkit/unidriver';
import { UniDriver } from '@wix/wix-ui-test-utils/unidriver';
import { SlidingModalUniDriver } from '../SlidingModal/SlidingModal.uni.driver';
import { CustomFieldPopoverUniDriver } from './CustomFieldPopover.uni.driver';
import { CustomFieldsDisabledHintUniDriver } from '../CustomFields/CustomFieldsDisabledHint.uni.driver';

export function CustomFieldPanelUniDriver(base: UniDriver, body: UniDriver) {
  const panelBase = () => base.$('[data-hook="custom-fields-panel"]');
  const panel = () => SidePanelUniDriver(panelBase(), body);

  const slidingModal = () =>
    SlidingModalUniDriver(base.$('[data-hook="cairo-side-panel-modal"]'), body);

  const addItem = () =>
    CustomFieldsDisabledHintUniDriver(base, body, {
      dataHook: 'data-extension-add-new',
    });

  const customFieldPanel = (i: number) =>
    CustomFieldPopoverUniDriver(getItemAtBase(i), body);

  const list = () => panelBase().$('[data-hook="custom-fields-list"]');
  const items = () => panelBase().$$('[data-hook="custom-fields-list"] > div');
  const getItemAtBase = (i: number) => items().get(i);

  const getItemByIdBase = (id: string) =>
    list().$(`[data-hook="custom-field-${id}"]`);

  return {
    exists: () => panelBase().exists(),
    isOpen: () =>
      Promise.all([slidingModal().isOpen(), panel().exists()]).then((arr) =>
        arr.every(Boolean),
      ),
    getTitle: () => panel().getTitleText(),
    getSubtitle: () => panel().getSubtitleText(),
    clickCloseButton: () => panel().clickClose(),
    closeButtonExists: () => panel().isCloseButtonExists(),
    getItemLabelById: (id: string) => getItemByIdBase(id).text(),
    getItemLabelByIndex: (i: number) => getItemAtBase(i).text(),
    getItemsCount: () => items().count(),
    getAddNewFieldButton: addItem,
    getCustomFieldOptionsAt: (i: number) =>
      customFieldPanel(i).getCustomFieldOptionsAt(),
  };
}
