import { useStoreApi } from "@xyflow/react";
import { useCallback, useMemo, useState } from "react";
import { flattenTasks, getProjection, reorderTasks } from "../StageNode.utils.js";
const useStageTaskDragHandler = ({ sequentialTaskGroups, sequentialTasks, onTaskReorder })=>{
    const storeApi = useStoreApi();
    const [activeDragId, setActiveDragId] = useState(null);
    const [offsetLeft, setOffsetLeft] = useState(0);
    const [overId, setOverId] = useState(null);
    const activeSequentialTask = useMemo(()=>sequentialTasks.find(({ task })=>task.id === activeDragId), [
        sequentialTasks,
        activeDragId
    ]);
    const isActiveTaskParallel = useMemo(()=>{
        if (!activeDragId) return false;
        const group = sequentialTaskGroups.find((g)=>g.some((t)=>t.id === activeDragId));
        return group ? group.length > 1 : false;
    }, [
        sequentialTaskGroups,
        activeDragId
    ]);
    const projected = useMemo(()=>{
        if (!activeDragId || !overId) return null;
        return getProjection(sequentialTaskGroups, activeDragId, overId, offsetLeft);
    }, [
        sequentialTaskGroups,
        activeDragId,
        overId,
        offsetLeft
    ]);
    const resetState = useCallback(()=>{
        setActiveDragId(null);
        setOffsetLeft(0);
        setOverId(null);
    }, []);
    const handleDragStart = useCallback((event)=>{
        setActiveDragId(event.active.id);
    }, []);
    const handleDragMove = useCallback((event)=>{
        setOffsetLeft(event.delta.x / storeApi.getState().transform[2]);
    }, [
        storeApi
    ]);
    const handleDragOver = useCallback((event)=>{
        setOverId(event.over?.id ?? null);
    }, []);
    const handleDragEnd = useCallback((event)=>{
        const { active, over } = event;
        const currentOffsetLeft = offsetLeft;
        resetState();
        if (!over) return;
        const projection = getProjection(sequentialTaskGroups, active.id, over.id, currentOffsetLeft);
        if (!projection) return;
        if (active.id === over.id) {
            const flattened = flattenTasks(sequentialTaskGroups);
            const activeTask = flattened.find((t)=>t.id === active.id);
            if (activeTask && activeTask.depth === projection.depth) return;
        }
        const newTasks = reorderTasks(sequentialTaskGroups, active.id, over.id, projection.depth);
        onTaskReorder(newTasks);
    }, [
        sequentialTaskGroups,
        onTaskReorder,
        offsetLeft,
        resetState
    ]);
    const handleDragCancel = useCallback(()=>{
        resetState();
    }, [
        resetState
    ]);
    return {
        activeDragId,
        activeSequentialTask,
        isActiveTaskParallel,
        projected,
        handleDragMove,
        handleDragOver,
        handleDragStart,
        handleDragEnd,
        handleDragCancel
    };
};
export { useStageTaskDragHandler };
