import React from 'react';
import { FiltersMap, KeyedItem } from '@wix/bex-core';
import { GridCardItemProps } from './GridCardItem';
import { GridBaseState, ItemActionsState } from '../../state';
import { ActionCellProps, TableActionCellPrimaryAction } from '../ActionCell';
import {
  CardGalleryItemProps,
  IconButton,
  PopoverMenu,
  PopoverMenuItemProps,
} from '@wix/design-system';
import { More } from '@wix/wix-ui-icons-common';
import { DisabledActionCellMenu } from '../ActionCell/DisabledActionCellMenu';
import {
  createPrimaryActionCellPropsWithBI,
  createSecondaryActionCellPropWithBi,
  reportOnPopoverMenuShow,
} from '../CollectionItemActions/CollectionItemActionsHelper';
import { getDefaultActionCellProps } from '../CollectionItemActions/getDefaultActionCellProps';
import { useExtensionMenuItems } from '../../hooks/useExtensionMenuItems';

interface ActionCell<T, F extends FiltersMap> {
  actionCell: GridCardItemProps<T, F>['actionCell'];
  item: T;
  index: number;
  gridState: GridBaseState<T, F>;
  keyedItem: KeyedItem<T>;
  itemActionsState: ItemActionsState<T, F>;
}

export function evaluateActionCell<T, F extends FiltersMap>({
  actionCell,
  item,
  index,
  gridState,
  keyedItem,
  itemActionsState,
}: ActionCell<T, F>): ActionCellProps {
  if (!actionCell) {
    return {};
  }

  if (typeof actionCell === 'function') {
    return actionCell(item, index, {
      openConfirmDeleteModal: itemActionsState.openConfirmDeleteModal,
      openConfirmModal: itemActionsState.openConfirmModal,
      collection: gridState.collection,
      keyedItem,
    });
  }

  return actionCell;
}

export function useGridItemActions<T, F extends FiltersMap>(
  actionCell: ActionCell<T, F> & {
    itemActionsState: ItemActionsState<T, F>;
    imagePlacement: string;
  },
) {
  const actions = evaluateActionCell(actionCell);

  let settingsMenu: CardGalleryItemProps['settingsMenu'] = null;
  let primaryAction: CardGalleryItemProps['primaryActionProps'] | null = null;

  const extensionMenuItems = useExtensionMenuItems({
    containerId: actions.containerId,
  });

  const secondaryActionCellPropsWithBI = createSecondaryActionCellPropWithBi({
    toolbarBIReporter: actionCell.gridState.toolbar.toolbarBIReporter,
    actionCellProps: actions,
    keyedItem: actionCell.keyedItem,
    extensionMenuItems,
  });

  const primaryActionCellPropsWithBI = createPrimaryActionCellPropsWithBI(
    actionCell.gridState.toolbar.toolbarBIReporter,
    actions,
    actionCell.keyedItem,
  ) as TableActionCellPrimaryAction;

  if (primaryActionCellPropsWithBI) {
    primaryAction = {
      label: primaryActionCellPropsWithBI.text,
      onClick: primaryActionCellPropsWithBI.onClick,
      disabled: primaryActionCellPropsWithBI.disabled,
      disabledMessage: primaryActionCellPropsWithBI.disabledMessage,
    };
  }

  if (actions.secondaryMenuDisabled) {
    settingsMenu = (
      <DisabledActionCellMenu
        dataHook="popover-icon-button-trigger-disabled"
        tooltipContent={
          actions.secondaryMenuDisabledTooltip ??
          actionCell.gridState.container.translate('cairo.disabled')
        }
        size="small"
        skin={actionCell.imagePlacement === 'top' ? 'light' : 'standard'}
        ariaLabel={actionCell.gridState.container.translate('cairo.moreActions')}
      />
    );
  } else if (
    secondaryActionCellPropsWithBI &&
    secondaryActionCellPropsWithBI.length > 0
  ) {
    settingsMenu = (
      <PopoverMenu
        {...actions.popoverMenuProps}
        {...getDefaultActionCellProps()}
        dataHook="popover"
        triggerElement={({ toggle, close }) => (
          <IconButton
            dataHook="popover-icon-button-trigger"
            onClick={(e) => {
              e.stopPropagation();
              toggle();
              reportOnPopoverMenuShow(
                actionCell.gridState.toolbar.toolbarBIReporter,
                actions,
                actionCell.keyedItem,
              );
            }}
            onPointerDown={
              actionCell.gridState._dnd ? (e) => e.stopPropagation() : undefined
            }
            onMouseLeave={close}
            skin={actionCell.imagePlacement === 'top' ? 'light' : 'standard'}
            size="small"
            priority="secondary"
          >
            <More />
          </IconButton>
        )}
        children={secondaryActionCellPropsWithBI.map((action, index) => {
          if (action.divider) {
            return <PopoverMenu.Divider key={index} />;
          }

          const { icon: prefixIcon, skin, ...rest } = action;

          return (
            <PopoverMenu.MenuItem
              key={index}
              prefixIcon={prefixIcon}
              skin={skin as PopoverMenuItemProps['skin']}
              {...rest}
            />
          );
        })}
      />
    );
  }

  return {
    primaryAction,
    settingsMenu,
  };
}
