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 } from '../ActionCell';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import {
  createPrimaryActionCellPropsWithBI,
  createSecondaryActionCellPropWithBi,
  reportOnPopoverMenuShow,
} from './CollectionItemActionsHelper';
import { getDefaultActionCellProps } from './getDefaultActionCellProps';
import { useExtensionMenuItems } from '../../hooks/useExtensionMenuItems';

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 { confirmModal } = state;
  const toolbarState = useToolbarCollectionContext();
  const { toolbarBIReporter } = toolbarState;
  const actionCellProps = renderActionCell?.(state) ?? {};
  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]);

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

  const primaryActionCellPropsWithBI = createPrimaryActionCellPropsWithBI(
    toolbarBIReporter,
    actionCellProps,
    keyedItem,
  );

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

export const CollectionItemActions = observer(_CollectionItemActions);
