import { jsx, jsxs } from "react/jsx-runtime";
import { Icon, Padding, Spacing } from "@uipath/apollo-core";
import { Column, Row } from "../../layouts/index.js";
import { Button, cn } from "@uipath/apollo-wind";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { EntryConditionIcon, ExitConditionIcon, ReturnToOriginIcon } from "../../icons/index.js";
import { CanvasIcon } from "../../utils/icon-registry.js";
import { CanvasTooltip } from "../CanvasTooltip.js";
import { ExecutionStatusIcon } from "../ExecutionStatusIcon/index.js";
import { getExecutionStatusColor } from "../ExecutionStatusIcon/ExecutionStatusIcon.js";
import { StageChip, StageHeader, StageHeaderChipsRow, StageTitleContainer, StageTitleInput } from "./StageNode.styles.js";
import { StageHeaderChipType } from "./StageNode.types.js";
const CHIP_ICONS = {
    [StageHeaderChipType.Entry]: /*#__PURE__*/ jsx(EntryConditionIcon, {
        w: Icon.IconXs,
        h: Icon.IconXs
    }),
    [StageHeaderChipType.Exit]: /*#__PURE__*/ jsx(ExitConditionIcon, {
        w: Icon.IconXs,
        h: Icon.IconXs
    }),
    [StageHeaderChipType.ReturnToOrigin]: /*#__PURE__*/ jsx(ReturnToOriginIcon, {
        w: Icon.IconXs,
        h: Icon.IconXs
    }),
    [StageHeaderChipType.CaseExit]: /*#__PURE__*/ jsx(CanvasIcon, {
        icon: "x",
        size: 16
    }),
    [StageHeaderChipType.CaseCompletion]: /*#__PURE__*/ jsx(CanvasIcon, {
        icon: "check",
        size: 16
    })
};
const StageNodeHeaderInner = ({ props, isReadOnly, isException, status, handleTaskAddClick })=>{
    const { id, stageDetails, execution, addTaskLabel = 'Add task', onTaskAdd, onAddTaskFromToolbox, onStageTitleChange, loadingTaskIds } = props;
    const isAddTaskDisabled = (loadingTaskIds?.size ?? 0) > 0;
    const icon = stageDetails?.icon;
    const statusLabel = execution?.stageStatus?.label;
    const stageDuration = execution?.stageStatus?.duration;
    const isStageTitleEditable = !!onStageTitleChange && !isReadOnly;
    const [isStageTitleEditing, setIsStageTitleEditing] = useState(false);
    const stageTitleRef = useRef(null);
    const [label, setLabel] = useState(props.stageDetails.label);
    useEffect(()=>{
        setLabel(props.stageDetails.label);
    }, [
        props.stageDetails.label
    ]);
    const handleStageTitleChange = useCallback((e)=>{
        setIsStageTitleEditing(true);
        setLabel(e.target.value);
    }, []);
    const handleStageTitleClickToSave = useCallback((e)=>{
        if (isStageTitleEditing && !stageTitleRef.current?.contains(e.target)) {
            setIsStageTitleEditing(false);
            if (onStageTitleChange) {
                if ('' === label.trim()) setLabel('Untitled Stage');
                onStageTitleChange(label);
            }
        }
    }, [
        isStageTitleEditing,
        onStageTitleChange,
        label
    ]);
    useEffect(()=>{
        if (isStageTitleEditing) document.addEventListener('click', handleStageTitleClickToSave);
        return ()=>{
            document.removeEventListener('click', handleStageTitleClickToSave);
        };
    }, [
        handleStageTitleClickToSave,
        isStageTitleEditing
    ]);
    const handleStageTitleBlurToSave = useCallback(()=>{
        if (isStageTitleEditing) {
            setIsStageTitleEditing(false);
            if (onStageTitleChange) {
                if ('' === label.trim()) setLabel('Untitled Stage');
                onStageTitleChange(label);
            }
        }
    }, [
        isStageTitleEditing,
        onStageTitleChange,
        label
    ]);
    const handleStageTitleKeyDown = useCallback((e)=>{
        if ('Enter' === e.key) {
            setIsStageTitleEditing(false);
            if (onStageTitleChange) onStageTitleChange(label);
        }
        if ('Escape' !== e.key) e.stopPropagation();
    }, [
        onStageTitleChange,
        label
    ]);
    return /*#__PURE__*/ jsxs(StageHeader, {
        isException: isException,
        "data-testid": `stage-header-${id}`,
        children: [
            /*#__PURE__*/ jsxs(Row, {
                gap: Spacing.SpacingMicro,
                align: "center",
                flex: 1,
                minW: 0,
                children: [
                    icon,
                    /*#__PURE__*/ jsxs(Column, {
                        py: 2,
                        flex: 1,
                        minW: 0,
                        children: [
                            /*#__PURE__*/ jsx("span", {
                                className: cn('text-sm', !isStageTitleEditing && 'font-bold'),
                                children: /*#__PURE__*/ jsx(CanvasTooltip, {
                                    content: label,
                                    placement: "top",
                                    delay: true,
                                    children: /*#__PURE__*/ jsx(StageTitleContainer, {
                                        isEditing: isStageTitleEditing,
                                        children: /*#__PURE__*/ jsx(StageTitleInput, {
                                            name: "Stage Title",
                                            isStageTitleEditable: isStageTitleEditable,
                                            value: label,
                                            ref: stageTitleRef,
                                            isEditing: isStageTitleEditing,
                                            ...onStageTitleChange && {
                                                onFocus: ()=>setIsStageTitleEditing(true),
                                                onInput: handleStageTitleChange,
                                                onKeyDown: handleStageTitleKeyDown,
                                                onBlur: handleStageTitleBlurToSave
                                            },
                                            readOnly: !isStageTitleEditable
                                        })
                                    })
                                })
                            }),
                            stageDuration && /*#__PURE__*/ jsx("span", {
                                className: "text-xs text-foreground-muted",
                                children: stageDuration
                            }),
                            stageDetails.headerChips && stageDetails.headerChips.length > 0 && /*#__PURE__*/ jsx(StageHeaderChipsRow, {
                                children: stageDetails.headerChips.map((chip)=>{
                                    const button = /*#__PURE__*/ jsxs(StageChip, {
                                        type: "button",
                                        "aria-label": 'string' == typeof chip.tooltip ? chip.tooltip : chip.type,
                                        onClick: (e)=>{
                                            e.stopPropagation();
                                            chip.onClick?.();
                                        },
                                        children: [
                                            CHIP_ICONS[chip.type],
                                            void 0 !== chip.count && /*#__PURE__*/ jsx("span", {
                                                className: "text-xs",
                                                children: chip.count
                                            })
                                        ]
                                    }, chip.type);
                                    if (chip.tooltip) return /*#__PURE__*/ jsx(CanvasTooltip, {
                                        placement: "bottom",
                                        content: chip.tooltip,
                                        children: button
                                    }, chip.type);
                                    return button;
                                })
                            })
                        ]
                    })
                ]
            }),
            /*#__PURE__*/ jsxs(Row, {
                gap: Spacing.SpacingMicro,
                align: "start",
                py: Padding.PadS,
                children: [
                    status && /*#__PURE__*/ jsx(CanvasTooltip, {
                        content: statusLabel,
                        placement: "top",
                        children: /*#__PURE__*/ jsx(Button, {
                            variant: "ghost",
                            size: "icon",
                            className: "h-6 w-6",
                            "aria-label": statusLabel,
                            children: 'NotExecuted' === status ? /*#__PURE__*/ jsx(CanvasIcon, {
                                icon: "hourglass",
                                size: 20,
                                color: getExecutionStatusColor('NotExecuted')
                            }) : /*#__PURE__*/ jsx(ExecutionStatusIcon, {
                                status: status,
                                size: 20
                            })
                        })
                    }),
                    (onTaskAdd || onAddTaskFromToolbox) && !isReadOnly && /*#__PURE__*/ jsx(CanvasTooltip, {
                        content: addTaskLabel,
                        placement: "top",
                        children: /*#__PURE__*/ jsx(Button, {
                            variant: "ghost",
                            size: "icon",
                            className: "h-6 w-6",
                            onClick: handleTaskAddClick,
                            "aria-label": addTaskLabel,
                            disabled: isAddTaskDisabled,
                            children: /*#__PURE__*/ jsx(CanvasIcon, {
                                icon: "plus",
                                size: 20
                            })
                        })
                    })
                ]
            })
        ]
    });
};
const StageNodeHeader = /*#__PURE__*/ memo(StageNodeHeaderInner);
export { StageNodeHeader };
