import { jsx, jsxs } from "react/jsx-runtime";
import { AutonomousAgentIcon, ConversationalAgentIcon, HealthScoreIcon } from "../../../icons/index.js";
import { Position } from "../../../xyflow/react.js";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { DefaultSuggestionTranslations } from "../../../types.js";
import { CanvasIcon } from "../../../utils/icon-registry.js";
import { BaseNode } from "../../BaseNode/BaseNode.js";
import { BaseNodeOverrideConfigProvider } from "../../BaseNode/BaseNodeConfigContext.js";
import { FloatingCanvasPanel } from "../../FloatingCanvasPanel/index.js";
import { ResourceNodeType } from "../AgentFlow.constants.js";
import { useAgentFlowStore } from "../store/agent-flow-store.js";
import { AddInstructionsButton, HealthScoreBadge, InstructionsLabel, InstructionsLine, InstructionsPreview, SettingsPreviewContainer, SettingsPreviewHeader, SettingsPreviewSubtitle, SettingsPreviewTitle, SettingsPromptBox, SettingsRow, SettingsRowLabel, SettingsRowValue, SettingsSection, SettingsSectionLabel, SettingsSectionValue, SubLabelContainer } from "./AgentNode.styles.js";
const HOVER_DELAY_MS = 500;
const HOVER_HIDE_DELAY_MS = 300;
const alwaysShowNotches = ()=>true;
const AgentNodeComponent = /*#__PURE__*/ memo((props)=>{
    const { id, data, selected = false, mode = 'design', hasMemory = false, hasContext = false, hasEscalation = false, hasTool = false, hasMcp = false, hasA2a = false, a2aEnabled = false, mcpEnabled = true, hasError = false, hasSuccess = false, hasRunning = false, onAddResource, onAddInstructions, translations, enableMemory, enableInstructions = false, healthScore, onHealthScoreClick, suggestionTranslations, suggestionGroupVersion, ...nodeProps } = props;
    const { actOnSuggestion } = useAgentFlowStore();
    const [isNodeHovered, setIsNodeHovered] = useState(false);
    const [isPanelHovered, setIsPanelHovered] = useState(false);
    const hoverTimeoutRef = useRef(null);
    const hideTimeoutRef = useRef(null);
    const showSettingsPreview = isNodeHovered || isPanelHovered;
    const { name, definition, suggestionId } = data;
    const isSuggestion = data.isSuggestion ?? false;
    const suggestionType = isSuggestion ? data.suggestionType : void 0;
    const isConversational = definition?.metadata?.isConversational === true;
    const suggestTranslations = suggestionTranslations ?? DefaultSuggestionTranslations;
    const agentIcon = useMemo(()=>{
        if (isConversational) return /*#__PURE__*/ jsx(ConversationalAgentIcon, {
            color: "var(--canvas-foreground-de-emp)",
            w: 32,
            h: 32
        });
        return /*#__PURE__*/ jsx(AutonomousAgentIcon, {
            color: "var(--canvas-foreground-de-emp)",
            w: 32,
            h: 32
        });
    }, [
        isConversational
    ]);
    const settings = definition?.settings;
    const handleMouseEnter = useCallback(()=>{
        if (!enableInstructions) return;
        if (hideTimeoutRef.current) {
            clearTimeout(hideTimeoutRef.current);
            hideTimeoutRef.current = null;
        }
        hoverTimeoutRef.current = setTimeout(()=>{
            setIsNodeHovered(true);
        }, HOVER_DELAY_MS);
    }, [
        enableInstructions
    ]);
    const handleMouseLeave = useCallback(()=>{
        if (!enableInstructions) return;
        if (hoverTimeoutRef.current) {
            clearTimeout(hoverTimeoutRef.current);
            hoverTimeoutRef.current = null;
        }
        hideTimeoutRef.current = setTimeout(()=>{
            setIsNodeHovered(false);
        }, HOVER_HIDE_DELAY_MS);
    }, [
        enableInstructions
    ]);
    const handlePanelMouseEnter = useCallback(()=>{
        if (hideTimeoutRef.current) {
            clearTimeout(hideTimeoutRef.current);
            hideTimeoutRef.current = null;
        }
        setIsPanelHovered(true);
    }, []);
    const handlePanelMouseLeave = useCallback(()=>{
        hideTimeoutRef.current = setTimeout(()=>{
            setIsPanelHovered(false);
        }, HOVER_HIDE_DELAY_MS);
    }, []);
    useEffect(()=>()=>{
            if (hoverTimeoutRef.current) clearTimeout(hoverTimeoutRef.current);
            if (hideTimeoutRef.current) clearTimeout(hideTimeoutRef.current);
        }, []);
    const executionStatus = useMemo(()=>{
        if (hasError) return 'Failed';
        if (hasSuccess) return 'Completed';
        if (hasRunning) return 'InProgress';
    }, [
        hasError,
        hasSuccess,
        hasRunning
    ]);
    const displayMemory = true === enableMemory && ('design' === mode || 'view' === mode && hasMemory);
    const displayContext = 'design' === mode || 'view' === mode && hasContext;
    const displayEscalation = 'design' === mode || 'view' === mode && hasEscalation;
    const displayTool = 'design' === mode || 'view' === mode && hasTool;
    const isMcpEnabled = false !== mcpEnabled;
    const displayMcp = 'design' === mode && isMcpEnabled || 'view' === mode && !!hasMcp;
    const isA2aEnabled = true === a2aEnabled;
    const displayA2a = 'design' === mode && isA2aEnabled || 'view' === mode && !!hasA2a;
    const handleConfigurations = useMemo(()=>{
        const configs = [];
        const topHandles = [];
        const bottomHandles = [];
        if (displayMemory) topHandles.push({
            id: ResourceNodeType.MemorySpace,
            type: 'source',
            handleType: 'artifact',
            label: translations.memory,
            showButton: 'design' === mode && !hasMemory,
            labelBackgroundColor: 'var(--canvas-background-secondary)',
            visible: displayMemory,
            onAction: (_e)=>{
                onAddResource?.('memorySpace');
            }
        });
        if (displayEscalation) topHandles.push({
            id: ResourceNodeType.Escalation,
            type: 'source',
            handleType: 'artifact',
            label: translations.escalations,
            showButton: 'design' === mode,
            labelBackgroundColor: 'var(--canvas-background-secondary)',
            visible: displayEscalation,
            onAction: (_e)=>{
                onAddResource?.('escalation');
            }
        });
        if (topHandles.length) configs.push({
            position: Position.Top,
            handles: topHandles,
            visible: true
        });
        if (displayContext || displayTool || displayMcp || displayA2a) {
            bottomHandles.push({
                id: ResourceNodeType.Context,
                type: 'source',
                handleType: 'artifact',
                label: translations.context,
                showButton: 'design' === mode,
                labelBackgroundColor: 'var(--canvas-background-secondary)',
                visible: displayContext,
                onAction: (_e)=>{
                    onAddResource?.('context');
                }
            }, {
                id: ResourceNodeType.Tool,
                type: 'source',
                handleType: 'artifact',
                label: translations.tools,
                showButton: 'design' === mode,
                labelBackgroundColor: 'var(--canvas-background-secondary)',
                visible: displayTool || displayMcp || displayA2a,
                onAction: (_e)=>{
                    if (displayTool) onAddResource?.('tool');
                    else if (displayMcp) onAddResource?.('mcp');
                    else if (displayA2a) onAddResource?.('a2a');
                }
            });
            configs.push({
                position: Position.Bottom,
                handles: bottomHandles,
                visible: true
            });
        }
        return configs;
    }, [
        mode,
        displayContext,
        displayMemory,
        displayMcp,
        displayTool,
        displayA2a,
        displayEscalation,
        hasMemory,
        onAddResource,
        translations
    ]);
    const healthScoreBadge = useMemo(()=>{
        if (void 0 === healthScore) return null;
        return /*#__PURE__*/ jsxs(HealthScoreBadge, {
            onClick: (e)=>{
                if (onHealthScoreClick) {
                    e.stopPropagation();
                    onHealthScoreClick();
                }
            },
            children: [
                /*#__PURE__*/ jsx(HealthScoreIcon, {
                    w: 14,
                    h: 14
                }),
                healthScore.toString()
            ]
        });
    }, [
        healthScore,
        onHealthScoreClick
    ]);
    const subLabelWithHealthScore = useMemo(()=>{
        const baseSubLabel = isConversational ? translations.conversationalAgent : translations.autonomousAgent;
        if (!healthScoreBadge) return baseSubLabel;
        return /*#__PURE__*/ jsxs(SubLabelContainer, {
            children: [
                /*#__PURE__*/ jsx("span", {
                    children: baseSubLabel
                }),
                healthScoreBadge
            ]
        });
    }, [
        isConversational,
        translations,
        healthScoreBadge
    ]);
    const { instructionsFooter, footerVariant } = useMemo(()=>{
        if (!enableInstructions) return {
            instructionsFooter: null,
            footerVariant: 'none'
        };
        const system = data.instructions?.system;
        const user = data.instructions?.user;
        const hasSystem = Boolean(system);
        const hasUser = Boolean(user);
        const hasContent = hasSystem || hasUser;
        if (hasContent) return {
            instructionsFooter: /*#__PURE__*/ jsxs(InstructionsPreview, {
                onClick: (e)=>{
                    e.stopPropagation();
                    onAddInstructions?.();
                },
                children: [
                    /*#__PURE__*/ jsx(InstructionsLabel, {
                        children: translations.instructions
                    }),
                    system && /*#__PURE__*/ jsxs(InstructionsLine, {
                        children: [
                            /*#__PURE__*/ jsxs("strong", {
                                children: [
                                    translations.system,
                                    ":"
                                ]
                            }),
                            ' "',
                            system,
                            '"'
                        ]
                    }),
                    user && /*#__PURE__*/ jsxs(InstructionsLine, {
                        children: [
                            /*#__PURE__*/ jsxs("strong", {
                                children: [
                                    translations.user,
                                    ":"
                                ]
                            }),
                            ' "',
                            user,
                            '"'
                        ]
                    })
                ]
            }),
            footerVariant: hasSystem && hasUser ? 'double' : 'single'
        };
        if ('design' !== mode || !onAddInstructions) return {
            instructionsFooter: null,
            footerVariant: 'none'
        };
        return {
            instructionsFooter: /*#__PURE__*/ jsxs(AddInstructionsButton, {
                type: "button",
                onClick: (e)=>{
                    e.stopPropagation();
                    onAddInstructions();
                },
                children: [
                    /*#__PURE__*/ jsx(CanvasIcon, {
                        icon: "plus",
                        size: 14
                    }),
                    translations.addInstructions
                ]
            }),
            footerVariant: 'button'
        };
    }, [
        enableInstructions,
        data.instructions,
        mode,
        onAddInstructions,
        translations
    ]);
    const shouldShowAddButtonFn = (opts)=>opts.showAddButton || opts.selected;
    const handleActOnSuggestion = useCallback((suggestionId, action)=>{
        actOnSuggestion(suggestionId, action);
    }, [
        actOnSuggestion
    ]);
    const toolbarConfig = useMemo(()=>{
        if ('view' === mode) return null;
        if (isSuggestion && suggestionId) {
            if ('0.0.1' === suggestionGroupVersion) return null;
            const rejectAction = {
                id: 'reject-suggestion',
                icon: 'x',
                label: suggestTranslations.reject,
                disabled: false,
                onAction: ()=>handleActOnSuggestion(suggestionId, 'reject')
            };
            const acceptAction = {
                id: 'accept-suggestion',
                icon: 'check',
                label: suggestTranslations.accept,
                disabled: false,
                onAction: ()=>handleActOnSuggestion(suggestionId, 'accept')
            };
            return {
                actions: [
                    rejectAction,
                    acceptAction
                ],
                overflowActions: [],
                overflowLabel: '',
                position: 'top',
                align: 'center'
            };
        }
        return null;
    }, [
        mode,
        isSuggestion,
        suggestionId,
        suggestionGroupVersion,
        suggestTranslations,
        handleActOnSuggestion
    ]);
    const settingsPreviewContent = useMemo(()=>{
        const systemPrompt = data.instructions?.system ?? '';
        const userPrompt = data.instructions?.user ?? '';
        return /*#__PURE__*/ jsxs(SettingsPreviewContainer, {
            children: [
                /*#__PURE__*/ jsxs(SettingsPreviewHeader, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsPreviewTitle, {
                            children: translations.agentSettings
                        }),
                        /*#__PURE__*/ jsx(SettingsPreviewSubtitle, {
                            children: translations.readOnlyPreview
                        })
                    ]
                }),
                settings?.model && /*#__PURE__*/ jsxs(SettingsSection, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsSectionLabel, {
                            children: translations.model
                        }),
                        /*#__PURE__*/ jsx(SettingsSectionValue, {
                            children: settings.model
                        })
                    ]
                }),
                /*#__PURE__*/ jsxs(SettingsSection, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsSectionLabel, {
                            children: translations.systemPrompt
                        }),
                        /*#__PURE__*/ jsx(SettingsPromptBox, {
                            isEmpty: !systemPrompt,
                            children: systemPrompt || translations.notConfigured
                        })
                    ]
                }),
                !isConversational && /*#__PURE__*/ jsxs(SettingsSection, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsSectionLabel, {
                            children: translations.userPrompt
                        }),
                        /*#__PURE__*/ jsx(SettingsPromptBox, {
                            isEmpty: !userPrompt,
                            children: userPrompt || translations.notConfigured
                        })
                    ]
                }),
                settings?.temperature !== void 0 && /*#__PURE__*/ jsxs(SettingsRow, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsRowLabel, {
                            children: translations.temperature
                        }),
                        /*#__PURE__*/ jsx(SettingsRowValue, {
                            children: settings.temperature
                        })
                    ]
                }),
                settings?.maxTokens !== void 0 && /*#__PURE__*/ jsxs(SettingsRow, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsRowLabel, {
                            children: translations.maxTokens
                        }),
                        /*#__PURE__*/ jsx(SettingsRowValue, {
                            children: settings.maxTokens
                        })
                    ]
                }),
                settings?.maxIterations !== void 0 && /*#__PURE__*/ jsxs(SettingsRow, {
                    children: [
                        /*#__PURE__*/ jsx(SettingsRowLabel, {
                            children: translations.maxIterations
                        }),
                        /*#__PURE__*/ jsx(SettingsRowValue, {
                            children: settings.maxIterations
                        })
                    ]
                })
            ]
        });
    }, [
        data.instructions,
        settings,
        translations,
        isConversational
    ]);
    const baseNodeConfig = useMemo(()=>({
            executionStatusOverride: executionStatus,
            suggestionType,
            handleConfigurations,
            toolbarConfig,
            footerVariant,
            iconComponent: agentIcon,
            footerComponent: instructionsFooter,
            subLabelComponent: subLabelWithHealthScore,
            shouldShowAddButtonFn,
            shouldShowButtonHandleNotchesFn: alwaysShowNotches
        }), [
        executionStatus,
        suggestionType,
        handleConfigurations,
        toolbarConfig,
        footerVariant,
        agentIcon,
        instructionsFooter,
        subLabelWithHealthScore,
        shouldShowAddButtonFn
    ]);
    return /*#__PURE__*/ jsxs("div", {
        onMouseEnter: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        children: [
            /*#__PURE__*/ jsx(BaseNodeOverrideConfigProvider, {
                value: baseNodeConfig,
                children: /*#__PURE__*/ jsx(BaseNode, {
                    ...nodeProps,
                    id: id,
                    type: isConversational ? 'uipath.agent.conversational' : 'uipath.agent.autonomous',
                    data: {
                        ...data,
                        display: {
                            label: name,
                            subLabel: isConversational ? translations.conversationalAgent : translations.autonomousAgent,
                            shape: 'rectangle',
                            background: 'var(--canvas-background)',
                            iconBackground: 'var(--canvas-background-secondary)'
                        }
                    },
                    selected: selected
                })
            }),
            /*#__PURE__*/ jsx(FloatingCanvasPanel, {
                open: showSettingsPreview,
                nodeId: id,
                placement: "right-start",
                offset: 16,
                onMouseEnter: handlePanelMouseEnter,
                onMouseLeave: handlePanelMouseLeave,
                children: settingsPreviewContent
            })
        ]
    });
});
AgentNodeComponent.displayName = 'AgentNodeComponent';
const AgentNodeWrapper = (props)=>{
    const { data, mode, hasMemory, hasContext, hasEscalation, hasTool, hasMcp, hasA2a, a2aEnabled, mcpEnabled, hasError, hasSuccess, hasRunning, onAddResource, onAddInstructions, translations, enableMemory, enableInstructions, healthScore, onHealthScoreClick, suggestionTranslations, suggestionGroupVersion, ...nodeProps } = props;
    return /*#__PURE__*/ jsx(AgentNodeComponent, {
        ...nodeProps,
        data: data,
        mode: mode,
        hasMemory: hasMemory,
        hasContext: hasContext,
        hasEscalation: hasEscalation,
        hasTool: hasTool,
        hasMcp: hasMcp,
        hasA2a: hasA2a,
        a2aEnabled: a2aEnabled,
        mcpEnabled: mcpEnabled,
        hasError: hasError,
        hasSuccess: hasSuccess,
        hasRunning: hasRunning,
        onAddResource: onAddResource,
        onAddInstructions: onAddInstructions,
        translations: translations,
        enableMemory: enableMemory,
        enableInstructions: enableInstructions,
        healthScore: healthScore,
        onHealthScoreClick: onHealthScoreClick,
        suggestionTranslations: suggestionTranslations,
        suggestionGroupVersion: suggestionGroupVersion
    });
};
const AgentNodeElement = /*#__PURE__*/ memo(AgentNodeWrapper);
export { AgentNodeElement };
