import { TableActionCell } from '@wix/design-system';
import React, { useEffect } from 'react';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { ItemActionsState } from '../../state';
import { MessageActionModal } from '../ActionModal';
import { ActionCellProps, TableActionCellMainAction } from '../ActionCell';
import { DisabledActionCellMenu } from '../ActionCell/DisabledActionCellMenu';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import {
  createPrimaryActionCellPropsWithBI,
  createSecondaryActionCellPropWithBi,
  reportOnPopoverMenuShow,
} from './CollectionItemActionsHelper';
import { getDefaultActionCellProps } from './getDefaultActionCellProps';
import { useExtensionMenuItems } from '../../hooks/useExtensionMenuItems';
import { useIsMobile } from '../../hooks/useIsMobile';
import { useBmHarmonyTheme } from '../../hooks/useBmHarmonyTheme';

export interface CollectionItemActionsProps<
  T,
  F extends FiltersMap = FiltersMap,
> {
  collection: CollectionState<T, F>;
  state: ItemActionsState<T, F>;
  renderActionCell?: (state: ItemActionsState<T, F>) => ActionCellProps;
}

function _CollectionItemActions<T, F extends FiltersMap = FiltersMap>({
  state,
  renderActionCell,
}: CollectionItemActionsProps<T, F>) {
  const isMobile = useIsMobile();
  const isBmHarmonyTheme = useBmHarmonyTheme();

  const { confirmModal } = state;
  const toolbarState = useToolbarCollectionContext();
  const { toolbarBIReporter } = toolbarState;
  const actionCellProps = renderActionCell?.(state) ?? {};
  const {
    secondaryMenuDisabled,
    secondaryMenuDisabledTooltip,
    ...tableActionCellProps
  } = actionCellProps;
  const keyedItem = state.actionCellAPI.keyedItem;

  const existingExtension = actionCellProps.containerId
    ? toolbarState.menuItemExtensions.get(actionCellProps.containerId)
    : undefined;

  const extensionMenuItems = useExtensionMenuItems({
    containerId: actionCellProps.containerId,
    extension: existingExtension,
  });

  useEffect(() => {
    if (extensionMenuItems && actionCellProps.containerId) {
      toolbarState.menuItemExtensions.set(
        actionCellProps.containerId,
        extensionMenuItems,
      );
    }
  }, [extensionMenuItems, actionCellProps.containerId]);

  if (secondaryMenuDisabled) {
    return (
      <DisabledActionCellMenu
        dataHook="collection-action-cell-disabled"
        tooltipContent={
          secondaryMenuDisabledTooltip ??
          toolbarState.container.translate('cairo.disabled')
        }
        size={actionCellProps.size ?? 'medium'}
        ariaLabel={toolbarState.container.translate('cairo.moreActions')}
      />
    );
  }

  const secondaryActionCellPropsWithBI = createSecondaryActionCellPropWithBi({
    toolbarBIReporter,
    actionCellProps,
    keyedItem,
    extensionMenuItems,
  });

  let primaryActionCellPropsWithBI = !isMobile
    ? createPrimaryActionCellPropsWithBI(
        toolbarBIReporter,
        actionCellProps,
        keyedItem,
      )
    : [];

  if (
    Array.isArray(primaryActionCellPropsWithBI) &&
    primaryActionCellPropsWithBI.length > 1
  ) {
    primaryActionCellPropsWithBI = primaryActionCellPropsWithBI.map(
      (action, index) => {
        return {
          ...action,
          priority:
            index ===
            (primaryActionCellPropsWithBI as TableActionCellMainAction[])
              .length! -
              1
              ? 'primary'
              : 'secondary',
        };
      },
    );
  }

  return (
    <>
      {confirmModal.value && (
        <MessageActionModal state={confirmModal} {...confirmModal.value} />
      )}
      <TableActionCell
        dataHook="collection-action-cell"
        {...tableActionCellProps}
        moreActionsProps={
          isBmHarmonyTheme
            ? {
                ...tableActionCellProps.moreActionsProps,
                priority: 'tertiary',
              }
            : tableActionCellProps.moreActionsProps
        }
        popoverMenuProps={{
          ...getDefaultActionCellProps(),
          onShow: () =>
            reportOnPopoverMenuShow(
              toolbarBIReporter,
              actionCellProps,
              state.keyedItem,
            ),
          ...actionCellProps.popoverMenuProps,
          ...getDefaultActionCellProps(),
        }}
        primaryAction={primaryActionCellPropsWithBI}
        secondaryActions={secondaryActionCellPropsWithBI}
      />
    </>
  );
}

export const CollectionItemActions = observer(_CollectionItemActions);
