import { type Ref, useEffect } from 'preact/hooks';
import Sortable from 'sortablejs';

export const useSortable = (
    listContainerRef: Readonly<Ref<HTMLElement>>,
    onListReorder: (params: { oldIndex: number; newIndex: number }) => void,
) =>
    useEffect(() => {
        if (!listContainerRef.current) {
            return;
        }

        const sortable = Sortable.create(listContainerRef.current, {
            onEnd: (event) => {
                if (
                    event.oldIndex === undefined ||
                    event.newIndex === undefined
                ) {
                    return;
                }

                onListReorder({
                    oldIndex: event.oldIndex,
                    newIndex: event.newIndex,
                });
            },
        });
        return () => {
            sortable.destroy();
        };
    }, [listContainerRef, onListReorder]);
