import { jsx, jsxs } from "react/jsx-runtime";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { areNodePropsEqualIgnoringPosition } from "../../utils/nodePropsEqual.js";
import { FloatingCanvasPanel } from "../FloatingCanvasPanel/index.js";
import { NodeContextMenu } from "../NodeContextMenu/index.js";
import { useSetNodeSelection } from "../NodePropertiesPanel/hooks/index.js";
import { Toolbox } from "../Toolbox/index.js";
import { INDENTATION_WIDTH, STAGE_CONTENT_INSET, StageContainer } from "./StageNode.styles.js";
import { StageNodeAllTaskGroups } from "./StageNodeAllTaskGroups.js";
import { StageNodeHandles } from "./StageNodeHandles.js";
import { StageNodeHeader } from "./StageNodeHeader.js";
import { useStageNodeLabels } from "./useStageNodeLabels.js";
const StageNodeInner = (props)=>{
    const labels = useStageNodeLabels();
    const { dragging, selected, id, width, execution, stageDetails, taskOptions = [], menuItems, pendingReplaceTask, onStageClick, onTaskAdd, onAddTaskFromToolbox, onTaskToolboxSearch, onReplaceTaskFromToolbox } = props;
    const taskWidth = width ? width - STAGE_CONTENT_INSET : void 0;
    const allTasks = useMemo(()=>stageDetails?.tasks || [], [
        stageDetails?.tasks
    ]);
    const isException = stageDetails?.isException;
    const isReadOnly = !!stageDetails?.isReadOnly;
    const selectedTaskId = stageDetails?.selectedTaskId;
    const status = execution?.stageStatus?.status;
    const [isHovered, setIsHovered] = useState(false);
    const handleMouseEnter = useCallback(()=>setIsHovered(true), []);
    const handleMouseLeave = useCallback(()=>setIsHovered(false), []);
    const taskStateReference = useRef({
        isParallel: false,
        groupIndex: -1,
        taskIndex: -1
    });
    const [isAddingTask, setIsAddingTask] = useState(false);
    const [isReplacingTask, setIsReplacingTask] = useState(false);
    useEffect(()=>{
        if (pendingReplaceTask) {
            const match = allTasks.flatMap((group, gi)=>group.map((task, ti)=>({
                        task,
                        groupIndex: gi,
                        taskIndex: ti
                    }))).find(({ task })=>task.id === selectedTaskId);
            if (match) {
                taskStateReference.current = {
                    isParallel: (allTasks[match.groupIndex]?.length ?? 0) > 1,
                    groupIndex: match.groupIndex,
                    taskIndex: match.taskIndex
                };
                setIsReplacingTask(true);
            }
        }
    }, [
        pendingReplaceTask,
        selectedTaskId,
        allTasks
    ]);
    useEffect(()=>{
        if (false === selected) {
            setIsAddingTask(false);
            setIsReplacingTask(false);
        }
    }, [
        selected
    ]);
    const shouldShowMenu = useMemo(()=>menuItems && menuItems.length > 0 && (selected || isHovered) && !isReadOnly, [
        menuItems,
        selected,
        isHovered,
        isReadOnly
    ]);
    const { setSelectedNodeId } = useSetNodeSelection();
    const handleStageClick = useCallback(()=>{
        onStageClick?.();
    }, [
        onStageClick
    ]);
    const handleTaskAddClick = useCallback((event)=>{
        event.stopPropagation();
        if (onTaskAdd) onTaskAdd();
        else if (onAddTaskFromToolbox) setIsAddingTask(true);
        setSelectedNodeId(id);
    }, [
        onTaskAdd,
        onAddTaskFromToolbox,
        setSelectedNodeId,
        id
    ]);
    const handleAddTaskToolboxItemSelected = useCallback((item)=>{
        onAddTaskFromToolbox?.(item);
        setIsAddingTask(false);
        setSelectedNodeId(id);
    }, [
        onAddTaskFromToolbox,
        setSelectedNodeId,
        id
    ]);
    const handleAddTaskToolboxClose = useCallback(()=>setIsAddingTask(false), []);
    const handleReplaceTaskToolboxClose = useCallback(()=>setIsReplacingTask(false), []);
    const handleReplaceTaskToolboxItemSelected = useCallback((item)=>{
        onReplaceTaskFromToolbox?.(item, taskStateReference.current.groupIndex, taskStateReference.current.taskIndex);
        setIsReplacingTask(false);
    }, [
        onReplaceTaskFromToolbox
    ]);
    const taskWidthStyle = useMemo(()=>taskWidth ? {
            '--stage-task-width': `${taskWidth}px`,
            '--stage-task-width-parallel': `${taskWidth - INDENTATION_WIDTH}px`
        } : void 0, [
        taskWidth
    ]);
    return /*#__PURE__*/ jsxs("div", {
        "data-testid": `stage-${id}`,
        className: "relative",
        onClick: handleStageClick,
        onMouseEnter: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        children: [
            /*#__PURE__*/ jsxs(StageContainer, {
                selected: selected,
                status: status,
                width: width,
                style: taskWidthStyle,
                children: [
                    /*#__PURE__*/ jsx(StageNodeHeader, {
                        props: props,
                        isReadOnly: isReadOnly,
                        isException: isException,
                        status: status,
                        handleTaskAddClick: handleTaskAddClick
                    }),
                    /*#__PURE__*/ jsx(StageNodeAllTaskGroups, {
                        props: props,
                        isReadOnly: isReadOnly,
                        taskWidthStyle: taskWidthStyle,
                        taskStateReference: taskStateReference,
                        setSelectedNodeId: setSelectedNodeId,
                        handleTaskAddClick: handleTaskAddClick,
                        setIsReplacingTask: setIsReplacingTask
                    })
                ]
            }),
            onAddTaskFromToolbox && isAddingTask && /*#__PURE__*/ jsx(FloatingCanvasPanel, {
                nodeId: id,
                offset: 15,
                children: /*#__PURE__*/ jsx(Toolbox, {
                    title: labels.addTask,
                    initialItems: taskOptions,
                    onClose: handleAddTaskToolboxClose,
                    onItemSelect: handleAddTaskToolboxItemSelected,
                    onSearch: onTaskToolboxSearch
                })
            }),
            onReplaceTaskFromToolbox && isReplacingTask && /*#__PURE__*/ jsx(FloatingCanvasPanel, {
                nodeId: id,
                offset: 15,
                children: /*#__PURE__*/ jsx(Toolbox, {
                    title: labels.replaceTask,
                    initialItems: taskOptions,
                    onClose: handleReplaceTaskToolboxClose,
                    onItemSelect: handleReplaceTaskToolboxItemSelected,
                    onSearch: onTaskToolboxSearch
                })
            }),
            menuItems && !dragging && /*#__PURE__*/ jsx(NodeContextMenu, {
                menuItems: menuItems,
                isVisible: shouldShowMenu
            }),
            /*#__PURE__*/ jsx(StageNodeHandles, {
                id: id,
                isReadOnly: isReadOnly,
                selected: selected,
                isHovered: isHovered,
                isException: isException
            })
        ]
    });
};
const StageNode = /*#__PURE__*/ memo(StageNodeInner, areNodePropsEqualIgnoringPosition);
export { StageNode };
