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 { observer } from 'mobx-react-lite';
import { usePageContext } from '@wix/bex-core/react';
import { KanbanState } from '../../state/KanbanState';
import { KanbanDragOverlayCardItem } from './KanbanDragOverlayCardItem';
import { KanbanBaseProps } from '../Kanban/KanbanProps';

const KanbanDragOverlayWrapper = forwardRef<
  HTMLDivElement,
  HTMLAttributes<HTMLDivElement>
>((props, ref) => <div data-hook="kanban-drag-overlay" ref={ref} {...props} />);

export interface KanbanDragOverlayProps<T, S, F extends FiltersMap> {
  state: KanbanState<T, S, F>;
  renderItem?: KanbanBaseProps<T, S, F>['renderItem'];
  actionCell?: KanbanBaseProps<T, S, F>['actionCell'];
  dataExtension?: KanbanBaseProps<T, S, F>['dataExtension'];
  tags?: KanbanBaseProps<T, S, F>['tags'];
}

function _KanbanDragOverlay<T, S, F extends FiltersMap>(
  props: KanbanDragOverlayProps<T, S, F>,
) {
  const { state, renderItem, actionCell, dataExtension, tags } = props;

  const { modalsContainerRef } = usePageContext();

  return createPortal(
    <DragOverlay
      modifiers={[restrictToWindowEdges]}
      wrapperElement={
        KanbanDragOverlayWrapper as
          | DragOverlayProps['wrapperElement']
          | ComponentType as DragOverlayProps['wrapperElement']
      }
    >
      <KanbanDragOverlayCardItem
        state={state}
        renderItem={renderItem}
        actionCell={actionCell}
        dataExtension={dataExtension}
        tags={tags}
      />
    </DragOverlay>,
    modalsContainerRef?.current ?? document.body,
  );
}

export const KanbanDragOverlay = observer(_KanbanDragOverlay);
