import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useMemo, useCallback, useState, useEffect, } from 'react';
import { DndContext, DragOverlay, KeyboardSensor, PointerSensor, useSensor, useSensors, } from '@dnd-kit/core';
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, arrayMove, } from '@dnd-kit/sortable';
import { DraggableEntityPanel } from './draggable-entity-panel';
import { DragOverlayEntity } from './drag-overlay-entity';
export const DraggablePanels = ({ path, panels, type, onDragEntity, }) => {
    const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
    }));
    const [draggablePanels, setDraggablePanels] = useState(panels);
    useEffect(() => setDraggablePanels(panels), [panels]);
    const [activePanel, setActivePanel] = useState();
    const panelsIds = useMemo(() => draggablePanels.map((panel) => panel.id), [draggablePanels]);
    const handleDragStart = useCallback((event) => {
        setActivePanel(draggablePanels.find((panel) => panel.id === event.active.id));
    }, [draggablePanels]);
    const handleDragEnd = useCallback((event) => {
        const { active, over } = event;
        setActivePanel(null);
        if (!over || active.id === (over === null || over === void 0 ? void 0 : over.id)) {
            return;
        }
        const activePanelIndex = draggablePanels.findIndex((panel) => panel.id === active.id);
        const overPanelIndex = draggablePanels.findIndex((panel) => panel.id === over.id);
        setDraggablePanels(arrayMove(draggablePanels, activePanelIndex, overPanelIndex));
        onDragEntity === null || onDragEntity === void 0 ? void 0 : onDragEntity(activePanelIndex, overPanelIndex);
    }, [draggablePanels, onDragEntity]);
    return (_jsxs(DndContext, { sensors: sensors, onDragStart: handleDragStart, onDragEnd: handleDragEnd, children: [_jsx(SortableContext, { items: panelsIds, strategy: verticalListSortingStrategy, children: draggablePanels.map((entity) => (_jsx(DraggableEntityPanel, { path: path, entity: entity, type: type }, entity.id))) }), _jsx(DragOverlay, { children: activePanel ? _jsx(DragOverlayEntity, { path: path, entity: activePanel, type: type }) : null })] }));
};
