import { useEffect, useRef } from 'preact/hooks';
import Sortable from 'sortablejs';
import { MarkerComponent } from './marker';
import { MarkersProps } from './types';

export const MarkersComponent = ({
    markers,
    onMarkersReorder,
}: MarkersProps) => {
    const listContainerRef = useRef<HTMLOListElement>(null);
    useEffect(() => {
        if (!listContainerRef.current) {
            return;
        }

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

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

    return (
        <ol ref={listContainerRef}>
            {markers.map((marker, i) => (
                <MarkerComponent
                    key={marker.key}
                    marker={marker}
                    isFirst={i === 0}
                    isLast={i === markers.length - 1}
                />
            ))}
        </ol>
    );
};
