import { FiltersMap, KeyedItem } from '@wix/bex-core';
import { ToolbarBIReporter } from '../../state/ToolbarBIReporter';
import {
  ActionCellProps,
  SecondaryAction,
  SecondaryActionAction,
  TableActionCellMainAction,
} from '../ActionCell';
import { action } from 'mobx';
import { createElement } from 'react';
import { ExtensionMenuItemsState } from '../../state';
import { TableActionCellSecondaryDivider } from '@wix/design-system';

const calcCtaCount = (actionCellProps: ActionCellProps) => {
  const { primaryAction, secondaryActions } = actionCellProps;
  const primaryActionLength = Array.isArray(primaryAction)
    ? primaryAction.length
    : primaryAction
    ? 1
    : 0;
  return (secondaryActions?.length || 0) + primaryActionLength;
};

type SecondaryActionDivider = Omit<
  TableActionCellSecondaryDivider,
  'divider'
> & {
  divider: true;
};
export type SecondaryActionOrDivider =
  | SecondaryActionAction
  | SecondaryActionDivider;

export const createSecondaryActionCellPropWithBi = <T, F extends FiltersMap>({
  toolbarBIReporter,
  actionCellProps,
  keyedItem,
  extensionMenuItems,
}: {
  toolbarBIReporter: ToolbarBIReporter<T, F>;
  actionCellProps: ActionCellProps;
  keyedItem: KeyedItem<T>;
  extensionMenuItems: ExtensionMenuItemsState;
}): SecondaryActionOrDivider[] => {
  const { primaryAction, secondaryActions = [] } = actionCellProps;
  const primaryActionLength = Array.isArray(primaryAction)
    ? primaryAction.length
    : primaryAction
    ? 1
    : 0;

  const moreSecondaryItems: SecondaryAction[] =
    extensionMenuItems.menuItems.map((menuItem) => {
      return {
        biName: menuItem.biName,
        dataHook: menuItem.dataHook,
        onClick: () => {
          menuItem.onClick({ selectedId: keyedItem.id });
        },
        text: menuItem.text,
        icon: menuItem.prefixIcon || createElement('div'),
        componentId: menuItem.componentId,
        appId: menuItem.appId,
      };
    }) || [];

  const allActions = [
    ...secondaryActions,
    ...moreSecondaryItems,
  ] as SecondaryActionOrDivider[];

  return (
    allActions.map((_action, index) => {
      const biIndex = index + 1;

      if (_action.divider) {
        return _action;
      }

      const onClick = action(() => {
        toolbarBIReporter.ctaClicked({
          location: 'actionCell',
          ctaIndex: primaryActionLength + biIndex,
          ctaName: _action?.biName || _action?.text || 'secondaryAction',
          moreActionsIndex: biIndex,
          numCtas: calcCtaCount(actionCellProps),
          itemIndex: keyedItem.index,
          itemId: keyedItem.id,
          componentId: _action.componentId,
          appId: _action.appId,
        });
        _action.onClick?.();
      });
      const { biName: _biName, ...wsrSecondaryAction } = _action;
      return { ...wsrSecondaryAction, onClick };
    }) || []
  );
};

export const createPrimaryActionCellPropsWithBI = <T, F extends FiltersMap>(
  toolbarBIReporter: ToolbarBIReporter<T, F>,
  actionCellProps: ActionCellProps,
  keyedItem: KeyedItem<T>,
): ActionCellProps['primaryAction'] => {
  const { primaryAction } = actionCellProps;
  if (primaryAction) {
    const addBiReport = (_primaryAction: TableActionCellMainAction) => {
      if (_primaryAction) {
        const onClick = action(() => {
          toolbarBIReporter.ctaClicked({
            location: 'actionCell',
            ctaIndex: 1,
            ctaName:
              _primaryAction?.biName || _primaryAction?.text || 'primaryAction',
            moreActionsIndex: 0,
            numCtas: calcCtaCount(actionCellProps),
            itemIndex: keyedItem.index,
            itemId: keyedItem.id,
          });
          _primaryAction?.onClick();
        });
        const { biName, ...wsrPrimaryAction } = _primaryAction;
        return { ...wsrPrimaryAction, onClick };
      }
      return _primaryAction;
    };

    if (Array.isArray(primaryAction)) {
      return primaryAction.map(addBiReport);
    } else {
      return addBiReport(primaryAction);
    }
  }
  return primaryAction;
};

export const reportOnPopoverMenuShow = <T, F extends FiltersMap>(
  toolbarBIReporter: ToolbarBIReporter<T, F>,
  actionCellProps: ActionCellProps,
  keyedItem: KeyedItem<T>,
) => {
  toolbarBIReporter.ctaClicked({
    location: 'actionCell',
    ctaIndex: 0,
    ctaName: 'More Actions Menu',
    numCtas: calcCtaCount(actionCellProps),
    itemId: keyedItem.id,
    itemIndex: keyedItem.index,
  });
};
