import { FiltersMap } from '@wix/bex-core';
import React, { ComponentType, HTMLAttributes, forwardRef } from 'react';
import {
  DragOverlay,
  DragOverlayProps,
} from '@wix/wix-style-react-incubator/dnd-kit/core';
import { createPortal } from 'react-dom';
import { restrictToWindowEdges } from '@wix/wix-style-react-incubator/dnd-kit/modifiers';
import { DraggableCardOverlayProps } from '../DragAndDrop';
import { GridDragOverlayCardItem } from './GridDragOverlayCardItem';
import { observer } from 'mobx-react-lite';
import { usePageContext } from '@wix/bex-core/react';

const DraggableCardOverlayWrapper = forwardRef<
  HTMLDivElement,
  HTMLAttributes<HTMLDivElement>
>((props, ref) => (
  <div data-hook="draggable-card-overlay" ref={ref} {...props} />
));

function _DraggableCardOverlay<T, F extends FiltersMap>(
  props: DraggableCardOverlayProps<T, F>,
) {
  const { state, renderItem } = props;

  const { _dnd } = state;

  const { modalsContainerRef } = usePageContext();

  return createPortal(
    <DragOverlay
      dropAnimation={_dnd?.dropAnimation}
      modifiers={[restrictToWindowEdges]}
      wrapperElement={
        DraggableCardOverlayWrapper as
          | DragOverlayProps['wrapperElement']
          | ComponentType as DragOverlayProps['wrapperElement']
      }
    >
      <GridDragOverlayCardItem renderItem={renderItem} state={state} />
    </DragOverlay>,
    modalsContainerRef?.current ?? document.body,
  );
}

export const DraggableCardOverlay = observer(_DraggableCardOverlay);
