import React, { ReactNode, useEffect } from 'react';
import {
  AutoScrollActivator,
  closestCenter,
  DndContext,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from '@wix/wix-style-react-incubator/dnd-kit/core';
import {
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@wix/wix-style-react-incubator/dnd-kit/sortable';
import { restrictToWindowEdges } from '@wix/wix-style-react-incubator/dnd-kit/modifiers';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import {
  CollectionDragAndDropParentState,
  CollectionDragAndDropState,
  DragAndDropSubmit,
} from '../DragAndDrop';
import { DragAndDropAnnouncements } from '../DragAndDrop/DragAndDropAnnouncements';
import { usePageContext } from '@wix/bex-core/react';

export interface ListDragAndDropContextProps<T, F extends FiltersMap> {
  state: CollectionDragAndDropParentState<T, F> & {
    collectionDragAndDropState: CollectionDragAndDropState<T, F> | null;
  };
  children?: ReactNode;
  onSubmit?: DragAndDropSubmit<T, F>;
}

function _ListDragAndDropContext<T, F extends FiltersMap>(
  props: ListDragAndDropContextProps<T, F>,
) {
  const { state: parentState, children, onSubmit } = props;

  const { keyedItems } = parentState.collection;

  const state =
    parentState.collectionDragAndDropState as CollectionDragAndDropState<T, F>;

  const { dnd } = state;

  const { modalsContainerRef } = usePageContext();

  const pointerSensor = useSensor(PointerSensor, {
    activationConstraint: dnd.activationConstraint,
  });

  const keyboardSensor = useSensor(KeyboardSensor, {
    keyboardCodes: dnd.keyboardCodes,
    coordinateGetter: sortableKeyboardCoordinates,
  });

  // in jsdom we mock drag-and-drop by setting a custom events to draggable elements
  const sensors = useSensors(
    ...(process.env.NODE_ENV === 'test' ? [] : [pointerSensor, keyboardSensor]),
  );

  useEffect(() => state.init(), []);

  dnd.onSubmit = onSubmit;

  return (
    <DndContext
      sensors={sensors}
      autoScroll={{
        activator: AutoScrollActivator.DraggableRect,
        acceleration: 4,
      }}
      accessibility={{
        container: modalsContainerRef.current as HTMLElement | undefined,
        announcements: dnd.nullAnnouncements,
        screenReaderInstructions: {
          draggable: '',
        },
        restoreFocus: false,
      }}
      collisionDetection={closestCenter}
      modifiers={[restrictToWindowEdges]}
      cancelDrop={(ev) => dnd.beforeDrop(ev)}
      onDragMove={(ev) => {
        dnd.onDragMove(ev);
      }}
      onDragStart={(ev) => {
        dnd.onDragStart(ev);
      }}
      onDragEnd={(ev) => {
        dnd.onDragEnd(ev);
      }}
      onDragCancel={() => {
        dnd.onDragCancel();
      }}
      onDragOver={(ev) => {
        dnd.onDragOver(ev);
      }}
    >
      <SortableContext
        items={keyedItems}
        strategy={verticalListSortingStrategy}
      >
        {children}
        <DragAndDropAnnouncements state={dnd} dataHook="list-dnd-live-region" />
      </SortableContext>
    </DndContext>
  );
}

export const ListDragAndDropContext = observer(_ListDragAndDropContext);
