import { jsx, jsxs } from "react/jsx-runtime";
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { Spacing } from "@uipath/apollo-core";
import { Row } from "../../layouts/index.js";
import { useCallback, useMemo } from "react";
import { GroupModificationType, moveGroupDown, moveGroupUp } from "../../utils/GroupModificationUtils.js";
import { DraggableTask } from "./DraggableTask.js";
import { useStageTaskDragHandler } from "./hooks/useStageTaskDragHandler.js";
import { StageParallelBracket, StageParallelLabel, StageTaskGroupContainer, StageTaskList } from "./StageNode.styles.js";
import { getContextMenuItems, getDivider } from "./StageNodeTaskUtilities.js";
import { StageTaskDragOverlay } from "./StageTaskDragOverlay.js";
const StageNodeSequentialTaskGroups = ({ props, sequentialTaskGroups, sequentialTasks, allTasks, isReadOnly, selectedTaskId, taskWidthStyle, hasContextMenu, handleTaskClick, handleReorderSequentialTasks, generateReplaceTaskMenuItemForTask })=>{
    const { execution, onTaskGroupModification, onTaskReorder, hideParallelOptions, loadingTaskIds } = props;
    const sequentialTaskIds = useMemo(()=>sequentialTasks.map(({ task })=>task.id), [
        sequentialTasks
    ]);
    const { activeDragId, activeSequentialTask, isActiveTaskParallel, projected, handleDragStart, handleDragMove, handleDragOver, handleDragEnd, handleDragCancel } = useStageTaskDragHandler({
        sequentialTaskGroups,
        sequentialTasks,
        onTaskReorder: handleReorderSequentialTasks
    });
    const handleTaskRegroup = useCallback((groupModificationType, groupIndex, taskIndex)=>{
        if (onTaskReorder && (groupModificationType === GroupModificationType.TASK_GROUP_UP || groupModificationType === GroupModificationType.TASK_GROUP_DOWN)) {
            const mover = groupModificationType === GroupModificationType.TASK_GROUP_UP ? moveGroupUp : moveGroupDown;
            const reordered = mover(sequentialTaskGroups, groupIndex, taskIndex);
            handleReorderSequentialTasks(reordered);
            return;
        }
        onTaskGroupModification?.(groupModificationType, groupIndex, taskIndex);
    }, [
        onTaskReorder,
        handleReorderSequentialTasks,
        onTaskGroupModification,
        sequentialTaskGroups
    ]);
    const buildContextMenuItems = useCallback((groupIndex, _, taskId)=>{
        const taskGroup = sequentialTaskGroups[groupIndex] ?? [];
        const isParallel = taskGroup.length > 1;
        const items = [];
        const replaceTaskMenuItem = generateReplaceTaskMenuItemForTask(taskId, isParallel);
        if (replaceTaskMenuItem) {
            items.push(replaceTaskMenuItem);
            items.push(getDivider());
        }
        let groupIndexInAllTasks;
        let taskIndexInAllTasks;
        for (const [allTasksGroupIndex, group] of allTasks.entries())for (const [allTasksTaskIndex, task] of group.entries())if (task.id === taskId) {
            groupIndexInAllTasks = allTasksGroupIndex;
            taskIndexInAllTasks = allTasksTaskIndex;
            break;
        }
        if (onTaskGroupModification && void 0 !== groupIndexInAllTasks && void 0 !== taskIndexInAllTasks) {
            const reGroupOptions = getContextMenuItems({
                isParallelGroup: isParallel,
                groupIndex,
                tasksLength: sequentialTaskGroups.length,
                groupIndexInAllTasks,
                taskIndexInAllTasks,
                isAboveParallel: (sequentialTaskGroups[groupIndex - 1]?.length ?? 0) > 1,
                isBelowParallel: (sequentialTaskGroups[groupIndex + 1]?.length ?? 0) > 1,
                reGroupTaskFunction: handleTaskRegroup,
                hideParallelOptions
            });
            return [
                ...items,
                ...reGroupOptions
            ];
        }
        return items;
    }, [
        onTaskGroupModification,
        sequentialTaskGroups,
        hideParallelOptions,
        handleTaskRegroup,
        generateReplaceTaskMenuItemForTask,
        allTasks
    ]);
    const sensors = useSensors(useSensor(PointerSensor, {
        activationConstraint: {
            distance: 3
        }
    }), useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates
    }));
    if (0 === sequentialTaskGroups.length) return null;
    return /*#__PURE__*/ jsxs(DndContext, {
        collisionDetection: closestCenter,
        sensors: sensors,
        onDragStart: handleDragStart,
        onDragMove: handleDragMove,
        onDragOver: handleDragOver,
        onDragEnd: handleDragEnd,
        onDragCancel: handleDragCancel,
        children: [
            /*#__PURE__*/ jsx(SortableContext, {
                items: sequentialTaskIds,
                strategy: verticalListSortingStrategy,
                children: /*#__PURE__*/ jsx(StageTaskList, {
                    className: "nodrag nopan",
                    children: sequentialTaskGroups.map((taskGroup, groupIndex)=>{
                        const isParallel = taskGroup.length > 1;
                        return /*#__PURE__*/ jsxs(Row, {
                            gap: Spacing.SpacingS,
                            children: [
                                isParallel && /*#__PURE__*/ jsx(StageParallelBracket, {}),
                                /*#__PURE__*/ jsxs(StageTaskGroupContainer, {
                                    isParallel: isParallel,
                                    children: [
                                        isParallel && /*#__PURE__*/ jsx(StageParallelLabel, {
                                            children: /*#__PURE__*/ jsx("span", {
                                                className: "text-xs",
                                                children: "Parallel"
                                            })
                                        }),
                                        taskGroup.map((task, taskIndex)=>{
                                            const taskExecution = execution?.taskStatus?.[task.id];
                                            return /*#__PURE__*/ jsx(DraggableTask, {
                                                task: task,
                                                taskExecution: taskExecution,
                                                isSelected: selectedTaskId === task.id,
                                                isParallel: isParallel,
                                                groupIndex: groupIndex,
                                                taskIndex: taskIndex,
                                                onTaskClick: handleTaskClick,
                                                projectedDepth: task.id === activeDragId && projected ? projected.depth : void 0,
                                                isDragDisabled: !onTaskReorder || isReadOnly,
                                                isTaskLoading: loadingTaskIds?.has(task.id),
                                                ...hasContextMenu && !isReadOnly && {
                                                    getContextMenuItems: buildContextMenuItems
                                                },
                                                isReadOnly: isReadOnly
                                            }, task.id);
                                        })
                                    ]
                                })
                            ]
                        }, `group-${groupIndex}`);
                    })
                })
            }),
            /*#__PURE__*/ jsx(StageTaskDragOverlay, {
                activeTask: activeSequentialTask?.task,
                isActiveTaskParallel: isActiveTaskParallel,
                taskWidthStyle: taskWidthStyle
            })
        ]
    });
};
export { StageNodeSequentialTaskGroups };
