import React, { useCallback, useEffect, useState } from 'react';
import { ItemActionsState } from '../state';
import { CollectionItemActions } from './CollectionItemActions';
import { CollectionState, FiltersMap, KeyedItem } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { ActionCell, ActionCellProps } from './ActionCell';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useToolbarCollectionContext } from './ToolbarCollectionContext';

export interface CollectionTableActionsColumnProps<T, F extends FiltersMap> {
  keyedItem: KeyedItem<T>;
  index: number;
  sticky?: boolean;
  actionCell: ActionCell<T, F>;
  collection: CollectionState<T, F>;
}

function _CollectionTableActionsColumn<T, F extends FiltersMap>(
  props: CollectionTableActionsColumnProps<T, F>,
) {
  const { experiments } = useWixPatternsContainer();
  const toolbarState = useToolbarCollectionContext<T, F>();
  const isActionCellSizeSmallEnabled = experiments.enabled(
    'specs.cairo.SmallActionCellSize',
  );
  const { collection, index, sticky, keyedItem, actionCell, ...rest } = props;

  const [state] = useState(
    () =>
      new ItemActionsState({
        keyedItem,
        collection,
        fade: 'static',
        reportBi: toolbarState.reportBi,
      }),
  );

  const renderActionCell = useCallback(() => {
    const actionCellProps =
      typeof actionCell === 'function'
        ? actionCell(keyedItem.item, index, state.actionCellAPI)
        : actionCell;

    return {
      ...actionCellProps,
      size: isActionCellSizeSmallEnabled
        ? 'small'
        : (actionCellProps.size as ActionCellProps['size']),
      popoverMenuProps: {
        // Larger zIndex than Page.Sticky https://github.com/wix-private/wix-design-systems/blob/844c42de1fb6e65f62b4b32538c5923869116d3d/packages/wix-style-react/src/Page/Page.st.css#L41
        ...(sticky && { zIndex: 1200 }),
        ...actionCellProps?.popoverMenuProps,
      },
    };
  }, [actionCell, sticky, index, keyedItem]);

  useEffect(() => {
    state.setItemIfChanged(keyedItem);
  }, [keyedItem]);

  return (
    <CollectionItemActions
      {...rest}
      collection={state.collection}
      renderActionCell={renderActionCell}
      state={state}
    />
  );
}

export const CollectionTableActionsColumn = observer(
  _CollectionTableActionsColumn,
);
