import React, { useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { Box } from '@wix/design-system';
import { FiltersMap } from '@wix/bex-core';
import { MultiLevelSortingState, SortableColumn } from '../../state';
import { ListDragAndDropContext } from '../ListDragAndDrop/ListDragAndDropContext';
import { DraggableListItem } from '../ListDragAndDrop/DraggableListItem';
import { MultiLevelSortingTableListItem } from './MultiLevelSortingTableListItem';
import { DraggableCardOverlay } from '../GridDragAndDropDndKit/DraggableCardOverlay';

export interface MultiLevelSortingListProps<T, F extends FiltersMap> {
  state: MultiLevelSortingState<T, F>;
}

export function _MultiLevelSortingList<T, F extends FiltersMap>(
  props: MultiLevelSortingListProps<T, F>,
) {
  const { state } = props;
  const { dragAndDrop } = state;

  const renderItem = useCallback(
    (
      sortableColumn: SortableColumn,
      index: number,
      { length }: { length: number },
    ) => {
      return (
        <DraggableListItem
          key={sortableColumn.key}
          id={sortableColumn.key}
          index={index}
          state={dragAndDrop}
        >
          <MultiLevelSortingTableListItem
            key={sortableColumn.key}
            sortableColumn={sortableColumn}
            index={index}
            state={state}
            showDivider={index < length - 1}
          />
        </DraggableListItem>
      );
    },
    [],
  );

  return (
    <ListDragAndDropContext
      state={dragAndDrop}
      onSubmit={async ({ from, over }) => {
        dragAndDrop._onSortReorder(from.item.columnId, over.item.columnId);
      }}
    >
      <>
        <Box
          direction="vertical"
          dataHook="multi-level-sorting-list"
          backgroundColor="D60"
        >
          {state.sortingCollection.result.items.map(renderItem)}
        </Box>
        <DraggableCardOverlay
          state={dragAndDrop}
          renderItem={(index) => {
            const item = state.sortingCollection.result.items[index];
            return item ? renderItem(item, index, { length: 0 }) : null;
          }}
        />
      </>
    </ListDragAndDropContext>
  );
}

export const MultiLevelSortingList = observer(_MultiLevelSortingList);
