import React, { useEffect, useRef } from 'react';
import { ActionCellProps } from '../ActionCell';
import { useExtensionMenuItems } from '../../hooks/useExtensionMenuItems';
import { FiltersMap } from '../../exports/core';
import { KanbanBaseProps, KanbanState } from '../../exports/alpha';
import { ItemActionsState } from '../../state';
import {
  IconButton,
  PopoverMenu,
  PopoverMenuItemProps,
} from '@wix/design-system';
import { getDefaultActionCellProps } from '../CollectionItemActions/getDefaultActionCellProps';
import { MoreSmall } from '@wix/wix-ui-icons-common';
import { DisabledActionCellMenu } from '../ActionCell/DisabledActionCellMenu';
import {
  createKanbanPrimaryActionCellPropsWithBI,
  createKanbanSecondaryActionCellPropsWithBI,
  reportOnKanbanPopoverMenuShow,
} from './KanbanCardActionsHelper';

interface CardActionCell<T, S, F extends FiltersMap> {
  actionCell: KanbanBaseProps<T, S, F>['actionCell'];
  originalItem: T;
  itemIndex: number;
  itemActionsState: ItemActionsState<T, F>;
  stageKey: string;
  cardKey: string;
  state: KanbanState<T, S, F>;
}

export function evaluateActionCell<T, S, F extends FiltersMap>({
  actionCell,
  originalItem,
  itemIndex,
  itemActionsState,
}: Omit<
  CardActionCell<T, S, F>,
  'stageKey' | 'cardKey' | 'state'
>): ActionCellProps {
  if (!actionCell) {
    return {};
  }

  if (typeof actionCell === 'function') {
    return actionCell(originalItem, itemIndex, itemActionsState.actionCellAPI);
  }

  return actionCell;
}

export function useCardActions<T, S, F extends FiltersMap>({
  actionCell,
  originalItem,
  itemIndex,
  itemActionsState,
  stageKey,
  cardKey,
  state,
}: CardActionCell<T, S, F>) {
  const actionCellConfig = evaluateActionCell({
    actionCell,
    originalItem,
    itemIndex,
    itemActionsState,
  });

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

  const secondaryActionCellPropsWithBI =
    createKanbanSecondaryActionCellPropsWithBI({
      state,
      actionCellProps: actionCellConfig,
      keyedItem: itemActionsState.keyedItem,
      extensionMenuItems,
      stageId: stageKey,
    });

  const primaryActionCellPropsWithBI = createKanbanPrimaryActionCellPropsWithBI(
    {
      state,
      actionCellProps: actionCellConfig,
      keyedItem: itemActionsState.keyedItem,
      stageId: stageKey,
    },
  );

  const popoverCloseRef = useRef<
    ((event: React.SyntheticEvent) => void) | null
  >(null);

  useEffect(() => {
    const closePopoverOnScroll = () => {
      if (popoverCloseRef.current) {
        const scrollEvent = new Event('scroll') as any;
        popoverCloseRef.current(scrollEvent);
      }
    };

    const stageCardsContainer = document.querySelector(
      `[data-hook="kanban-stage-cards-container-${stageKey}"]`,
    );

    if (
      stageCardsContainer &&
      typeof stageCardsContainer.addEventListener === 'function'
    ) {
      stageCardsContainer.addEventListener('scroll', closePopoverOnScroll, {
        passive: true,
      });

      return () => {
        if (typeof stageCardsContainer.removeEventListener === 'function') {
          stageCardsContainer.removeEventListener(
            'scroll',
            closePopoverOnScroll,
          );
        }
      };
    }

    return () => {};
  }, [stageKey]);

  let secondaryActions: React.ReactNode | null = null;

  if (actionCellConfig.secondaryMenuDisabled) {
    secondaryActions = (
      <DisabledActionCellMenu
        dataHook={`kanban-card-more-actions-trigger-disabled-${stageKey}-${cardKey}`}
        tooltipContent={
          actionCellConfig.secondaryMenuDisabledTooltip ??
          state.container.translate('cairo.disabled')
        }
        size="tiny"
        icon={<MoreSmall />}
        ariaLabel={state.container.translate('cairo.moreActions')}
      />
    );
  } else if (
    secondaryActionCellPropsWithBI &&
    secondaryActionCellPropsWithBI.length > 0
  ) {
    secondaryActions = (
      <PopoverMenu
        {...actionCellConfig.popoverMenuProps}
        {...getDefaultActionCellProps()}
        textSize="small"
        minWidth="223px"
        dataHook={`kanban-card-more-actions-${stageKey}-${cardKey}`}
        triggerElement={({ toggle, close }) => {
          popoverCloseRef.current = close;

          return (
            <IconButton
              dataHook={`kanban-card-more-actions-trigger-${stageKey}-${cardKey}`}
              onClick={(e) => {
                e.stopPropagation();
                toggle();
                reportOnKanbanPopoverMenuShow({
                  state,
                  keyedItem: itemActionsState.keyedItem,
                  stageId: stageKey,
                });
              }}
              priority="secondary"
              size="tiny"
            >
              <MoreSmall />
            </IconButton>
          );
        }}
      >
        {secondaryActionCellPropsWithBI.map((action, index) => {
          if (action.divider) {
            return <PopoverMenu.Divider key={index} />;
          }
          const { icon: prefixIcon, skin, ...rest } = action;
          return (
            <PopoverMenu.MenuItem
              key={index}
              subtitle={action.disabledDescription}
              prefixIcon={prefixIcon}
              dataHook={
                action.dataHook ||
                `kanban-card-more-actions-item-${stageKey}-${cardKey}-${index}`
              }
              skin={skin as PopoverMenuItemProps['skin']}
              {...rest}
            />
          );
        })}
      </PopoverMenu>
    );
  }
  return {
    secondaryActions,
    primaryActionProps: primaryActionCellPropsWithBI,
  };
}
