import React, { type ReactNode } from 'react';
import { PopoverMenu, Loader } from '@wix/design-system';
import type { HeaderAction } from './headerActionTypes';

/**
 * Renders grouped field actions as PopoverMenu items, with a divider between
 * groups. Shared by HeaderActionsPopover (table header) and FieldActionsPopover
 * (side panels) so the menu body is identical across surfaces; only the trigger
 * differs. Returns an empty array when there are no actions.
 */
export function actionMenuItems(actions: HeaderAction[][]): ReactNode[] {
  return actions
    .filter((group) => group.length > 0)
    .reduce<ReactNode[]>((result, group, index, array) => {
      const items = group.map((action, i) => (
        <PopoverMenu.MenuItem
          key={`${index}-${i}`}
          dataHook={action.dataHook}
          text={action.label}
          onClick={
            action.disabled || action.loading ? undefined : action.onClick
          }
          prefixIcon={
            action.loading ? (
              <span>
                <Loader size="tiny" />
              </span>
            ) : (
              action.icon
            )
          }
          disabled={action.disabled || action.loading}
          disabledDescription={
            action.loading ? undefined : action.disabledTooltip
          }
          skin={action.skin}
        />
      ));
      const divider =
        index < array.length - 1
          ? [<PopoverMenu.Divider key={`divider-${index}`} />]
          : [];
      return [...result, ...items, ...divider];
    }, []);
}
