import { ActionSubitem } from '../../components/ActionControl/ActionSubItemProps';
import { MoreActionsItem } from '../../components/MoreActions/MoreActionsItem';
import { SecondaryActionsElement } from '../../components/SecondaryActions/SecondaryActions';
import { MoreActionsPropItem } from '../../components/MoreActions/MoreActionsBase';

function normalizeToGroups<T>(items: T[] | T[][] | undefined): T[][] {
  if (!items || items.length === 0) {
    return [];
  }
  return Array.isArray(items[0]) ? (items as T[][]) : [items as T[]];
}

function toMoreActionsItem(subitem: ActionSubitem): MoreActionsItem {
  return {
    text: subitem.label ?? '',
    onClick: subitem.onClick ?? (() => {}),
    prefixIcon: subitem.prefixIcon,
    disabled: subitem.disabled,
    subtitle: subitem.subtitle,
    dataHook: subitem.dataHook,
    biName: subitem.biName,
    biAdditionalInfo: subitem.biAdditionalInfo,
  };
}

function secondaryActionsToGroups(
  secondaryActions: SecondaryActionsElement | undefined,
): MoreActionsPropItem[][] {
  if (!secondaryActions) {
    return [];
  }

  const {
    label,
    onClick,
    prefixIcon,
    disabled,
    biName,
    biAdditionalInfo,
    subItems,
  } = secondaryActions.props;

  if (subItems && subItems.length > 0) {
    return normalizeToGroups(subItems).map((group) =>
      group.map(toMoreActionsItem),
    );
  }

  if (label) {
    return [
      [
        {
          text: label,
          onClick: onClick ?? (() => {}),
          prefixIcon,
          disabled,
          biName,
          biAdditionalInfo,
        },
      ],
    ];
  }

  return [];
}

export function mergeActionsForNarrowMode(
  secondaryActions: SecondaryActionsElement | undefined,
  moreActionsItems: MoreActionsPropItem[] | MoreActionsPropItem[][] | undefined,
): MoreActionsPropItem[][] {
  const secondaryGroups = secondaryActionsToGroups(secondaryActions);
  const moreActionsGroups = normalizeToGroups(moreActionsItems);
  return [...secondaryGroups, ...moreActionsGroups];
}
