import { useCallback, useMemo } from 'react';

import { useSidebarContext } from '@composed-components/LibrariesSidebar/context';
import { getReorderedItems } from '@composed-components/LibrariesSidebar/utils';
import { type DragEvent } from '@composed-components/SortableListComposition/types';

export const useSortableList = (parentId?: number) => {
  const { isSortMode, getOrderedItems, setPendingSort } = useSidebarContext();

  const listItems = useMemo(
    () => getOrderedItems(parentId),
    [getOrderedItems, parentId],
  );

  const handleDragEnd = useCallback(
    (event: DragEvent) => {
      setPendingSort(
        getReorderedItems(listItems, event.active, event.over),
        parentId,
      );
    },
    [listItems, setPendingSort, parentId],
  );

  return { isSortMode, listItems, handleDragEnd };
};
