import { jsx } from "react/jsx-runtime";
import { A2aIcon, ContextIcon, McpIcon, MemoryIcon } from "../../../icons/index.js";
import { Row } from "../../../layouts/index.js";
import { CanvasIcon } from "../../../utils/index.js";
import { Position } from "../../../xyflow/react.js";
import { memo, useCallback, useMemo } from "react";
import { DefaultSuggestionTranslations } from "../../../types.js";
import { BaseNode } from "../../BaseNode/BaseNode.js";
import { BaseNodeOverrideConfigProvider } from "../../BaseNode/BaseNodeConfigContext.js";
import { ExecutionStatusIcon } from "../../ExecutionStatusIcon/ExecutionStatusIcon.js";
import { ToolResourceIcon } from "../components/ToolResourceIcon/index.js";
import { useAgentFlowStore, useEdges } from "../store/agent-flow-store.js";
const alwaysShowNotches = ()=>true;
const ResourceNode = /*#__PURE__*/ memo(({ data, selected, id, mode, hasError = false, hasSuccess = false, hasRunning = false, onEnable, onDisable, onAddBreakpoint, onRemoveBreakpoint, onAddGuardrail, onGoToSource, onErrorAction, translations, suggestionTranslations, suggestionGroupVersion, ...nodeProps })=>{
    const { nodes: _nodes, deleteNode, actOnSuggestion } = useAgentFlowStore();
    const edges = useEdges();
    const connectedHandlePosition = useMemo(()=>{
        const nodeEdge = edges.find((e)=>e.target === id);
        return nodeEdge?.targetHandle;
    }, [
        edges,
        id
    ]);
    const displayTooltips = 'design' === mode;
    const hasBreakpoint = data.hasBreakpoint ?? false;
    const hasGuardrails = data.hasGuardrails ?? false;
    const isCurrentBreakpoint = data.isCurrentBreakpoint ?? false;
    const isDisabled = data.isDisabled ?? false;
    const isSuggestion = data.isSuggestion ?? false;
    const suggestionId = data.suggestionId;
    const suggestionType = isSuggestion ? data.suggestionType : void 0;
    const suggestTranslations = suggestionTranslations ?? DefaultSuggestionTranslations;
    const errorAction = data.errorAction ?? void 0;
    const handleClickEnable = useCallback(()=>{
        onEnable?.(id, data);
    }, [
        id,
        data,
        onEnable
    ]);
    const handleClickDisable = useCallback(()=>{
        onDisable?.(id, data);
    }, [
        id,
        data,
        onDisable
    ]);
    const handleClickAddBreakpoint = useCallback(()=>{
        onAddBreakpoint?.(id, data);
    }, [
        id,
        data,
        onAddBreakpoint
    ]);
    const handleClickRemoveBreakpoint = useCallback(()=>{
        onRemoveBreakpoint?.(id, data);
    }, [
        id,
        data,
        onRemoveBreakpoint
    ]);
    const handleClickAddGuardrail = useCallback(()=>{
        onAddGuardrail?.(id, data);
    }, [
        id,
        data,
        onAddGuardrail
    ]);
    const handleClickGoToSource = useCallback(()=>{
        onGoToSource?.(id, data);
    }, [
        id,
        data,
        onGoToSource
    ]);
    const handleClickRemove = useCallback(()=>{
        deleteNode(id);
    }, [
        id,
        deleteNode
    ]);
    const handleClickErrorAction = useCallback(()=>{
        onErrorAction?.(id, data);
    }, [
        id,
        data,
        onErrorAction
    ]);
    const handleActOnSuggestion = useCallback((suggestionId, action)=>{
        actOnSuggestion(suggestionId, action);
    }, [
        actOnSuggestion
    ]);
    const executionStatus = useMemo(()=>{
        if (isCurrentBreakpoint) return 'Paused';
        if (hasError) return 'Failed';
        if (hasSuccess) return 'Completed';
        if (hasRunning) return 'InProgress';
    }, [
        hasError,
        hasSuccess,
        hasRunning,
        isCurrentBreakpoint
    ]);
    const resourceIcon = useMemo(()=>{
        let icon;
        switch(data.type){
            case 'context':
                icon = /*#__PURE__*/ jsx(ContextIcon, {
                    w: 40,
                    h: 40
                });
                break;
            case 'escalation':
                icon = /*#__PURE__*/ jsx(CanvasIcon, {
                    icon: "user",
                    size: 40
                });
                break;
            case 'memorySpace':
                icon = /*#__PURE__*/ jsx(MemoryIcon, {
                    w: 40,
                    h: 40
                });
                break;
            case 'mcp':
                icon = /*#__PURE__*/ jsx(McpIcon, {
                    w: 40,
                    h: 40
                });
                break;
            case 'a2a':
                icon = /*#__PURE__*/ jsx(A2aIcon, {
                    w: 40,
                    h: 40
                });
                break;
            case 'tool':
                icon = /*#__PURE__*/ jsx(ToolResourceIcon, {
                    size: 48,
                    tool: data
                });
                break;
            default:
                icon = void 0;
                break;
        }
        return icon ? /*#__PURE__*/ jsx(Row, {
            style: {
                color: 'var(--canvas-foreground-de-emp)'
            },
            children: icon
        }) : null;
    }, [
        data
    ]);
    const toolbarConfig = useMemo(()=>{
        if ('view' === mode || data.isPlaceholder && (!isSuggestion || !suggestionId)) return null;
        if (isSuggestion && suggestionId) {
            if ('0.0.1' === suggestionGroupVersion) return null;
            const rejectAction = {
                id: 'reject-suggestion',
                icon: /*#__PURE__*/ jsx(CanvasIcon, {
                    icon: "X",
                    size: 14
                }),
                label: suggestTranslations.reject,
                disabled: false,
                onAction: ()=>handleActOnSuggestion(suggestionId, 'reject')
            };
            const acceptAction = {
                id: 'accept-suggestion',
                icon: /*#__PURE__*/ jsx(CanvasIcon, {
                    icon: "check",
                    size: 14
                }),
                label: suggestTranslations.accept,
                disabled: false,
                onAction: ()=>handleActOnSuggestion(suggestionId, 'accept')
            };
            return {
                actions: [
                    rejectAction,
                    acceptAction
                ],
                overflowActions: [],
                overflowLabel: '',
                position: 'top',
                align: 'center'
            };
        }
        const toggleBreakpointAction = {
            id: 'toggle-breakpoint',
            icon: void 0,
            label: (hasBreakpoint ? translations?.removeBreakpoint : translations?.addBreakpoint) ?? '',
            disabled: false,
            onAction: hasBreakpoint ? handleClickRemoveBreakpoint : handleClickAddBreakpoint
        };
        const addGuardrailAction = {
            id: 'add-guardrail',
            icon: void 0,
            label: translations?.addGuardrail ?? '',
            disabled: false,
            onAction: handleClickAddGuardrail
        };
        const goToSourceAction = {
            id: 'go-to-source',
            icon: void 0,
            label: translations?.goToSource ?? '',
            disabled: false,
            onAction: handleClickGoToSource
        };
        const removeAction = {
            id: 'remove',
            icon: /*#__PURE__*/ jsx(CanvasIcon, {
                icon: "trash",
                size: 14
            }),
            label: translations?.remove ?? '',
            disabled: false,
            onAction: handleClickRemove
        };
        const errorCtaAction = {
            id: 'error-cta',
            icon: errorAction?.icon ?? '',
            label: errorAction?.label ?? '',
            disabled: false,
            onAction: handleClickErrorAction
        };
        const toggleEnabledAction = {
            id: 'toggle-enabled',
            icon: void 0,
            label: (isDisabled ? translations?.enable : translations?.disable) ?? '',
            disabled: false,
            onAction: isDisabled ? handleClickEnable : handleClickDisable
        };
        const separator = {
            id: 'separator',
            icon: void 0,
            label: void 0,
            disabled: false,
            onAction: ()=>{}
        };
        const actions = [
            removeAction,
            ...errorAction ? [
                errorCtaAction
            ] : []
        ];
        const overflowActions = [
            toggleBreakpointAction,
            ...'tool' === data.type ? [
                addGuardrailAction
            ] : [],
            ...data.projectId ? [
                goToSourceAction
            ] : [],
            ...'tool' === data.type ? [
                separator,
                toggleEnabledAction
            ] : []
        ];
        return {
            actions,
            overflowActions,
            overflowLabel: translations?.moreOptions ?? '',
            position: 'top',
            align: 'center'
        };
    }, [
        mode,
        data.projectId,
        data.type,
        data.isPlaceholder,
        hasBreakpoint,
        isDisabled,
        isSuggestion,
        suggestionId,
        suggestionGroupVersion,
        handleClickEnable,
        handleClickDisable,
        handleClickRemoveBreakpoint,
        handleClickAddBreakpoint,
        translations,
        handleClickAddGuardrail,
        handleClickGoToSource,
        handleClickRemove,
        handleClickErrorAction,
        handleActOnSuggestion,
        suggestTranslations,
        errorAction
    ]);
    const toolTopHandles = useMemo(()=>[
            {
                id: Position.Top,
                type: 'target',
                handleType: 'artifact',
                showButton: false
            }
        ], []);
    const toolBottomHandles = useMemo(()=>[
            {
                id: Position.Bottom,
                type: 'source',
                handleType: 'artifact',
                showButton: false
            }
        ], []);
    const contextHandles = useMemo(()=>[
            {
                id: Position.Top,
                type: 'source',
                handleType: 'artifact',
                showButton: false
            }
        ], []);
    const escalationHandles = useMemo(()=>[
            {
                id: Position.Bottom,
                type: 'target',
                handleType: 'artifact',
                showButton: false
            }
        ], []);
    const memoryHandles = useMemo(()=>[
            {
                id: Position.Bottom,
                type: 'target',
                handleType: 'artifact',
                showButton: false
            }
        ], []);
    const breakpointAdornment = useMemo(()=>{
        if (!hasBreakpoint) return;
        return /*#__PURE__*/ jsx(CanvasIcon, {
            icon: "circle",
            size: 14,
            color: "#cc3d45"
        });
    }, [
        hasBreakpoint
    ]);
    const statusAdornment = useMemo(()=>/*#__PURE__*/ jsx(ExecutionStatusIcon, {
            status: executionStatus,
            size: 16
        }), [
        executionStatus
    ]);
    const guardrailsAdornment = useMemo(()=>{
        if (!hasGuardrails) return;
        return /*#__PURE__*/ jsx(CanvasIcon, {
            icon: "shield-check",
            size: 18,
            color: "var(--canvas-icon-default)"
        });
    }, [
        hasGuardrails
    ]);
    const suggestionAdornment = useMemo(()=>{
        if (!isSuggestion) return;
        let iconName = 'arrow-left-right';
        let color = 'var(--canvas-warning-icon)';
        if ('add' === suggestionType) {
            iconName = 'circle-plus';
            color = 'var(--canvas-success-icon)';
        } else if ('delete' === suggestionType) {
            iconName = 'circle-minus';
            color = 'var(--canvas-error-icon)';
        }
        return /*#__PURE__*/ jsx(CanvasIcon, {
            icon: iconName,
            size: 18,
            color: color
        });
    }, [
        isSuggestion,
        suggestionType
    ]);
    const handleConfigurations = useMemo(()=>[
            {
                position: Position.Top,
                handles: toolTopHandles,
                visible: ('tool' === data.type || 'mcp' === data.type || 'a2a' === data.type) && connectedHandlePosition === Position.Top
            },
            ...data.isExpandable ? [
                {
                    position: Position.Bottom,
                    handles: toolBottomHandles,
                    visible: ('tool' === data.type || 'mcp' === data.type || 'a2a' === data.type) && connectedHandlePosition === Position.Bottom
                }
            ] : [],
            {
                position: Position.Top,
                handles: contextHandles,
                visible: 'context' === data.type && connectedHandlePosition === Position.Top
            },
            {
                position: Position.Bottom,
                handles: escalationHandles,
                visible: 'escalation' === data.type && connectedHandlePosition === Position.Bottom
            },
            {
                position: Position.Bottom,
                handles: memoryHandles,
                visible: 'memorySpace' === data.type && connectedHandlePosition === Position.Bottom
            }
        ], [
        data.type,
        data.isExpandable,
        connectedHandlePosition,
        toolTopHandles,
        toolBottomHandles,
        contextHandles,
        escalationHandles,
        memoryHandles
    ]);
    const getResourceNodeType = ()=>{
        switch(data.type){
            case 'context':
                return 'uipath.resource.context';
            case 'tool':
                return 'uipath.resource.tool';
            case 'mcp':
                return 'uipath.resource.mcp';
            case 'escalation':
                return 'uipath.resource.escalation';
            case 'memorySpace':
                return 'uipath.resource.memory';
            case 'a2a':
                return 'uipath.resource.a2a';
            default:
                return 'uipath.resource.tool';
        }
    };
    const baseNodeConfig = useMemo(()=>({
            labelTooltip: displayTooltips ? data.description : void 0,
            labelBackgroundColor: 'var(--canvas-background-secondary)',
            disabled: isDisabled,
            executionStatusOverride: executionStatus,
            suggestionType,
            iconComponent: resourceIcon,
            handleConfigurations,
            toolbarConfig,
            adornments: {
                topLeft: breakpointAdornment,
                topRight: statusAdornment,
                bottomLeft: suggestionAdornment,
                bottomRight: guardrailsAdornment
            },
            shouldShowButtonHandleNotchesFn: alwaysShowNotches
        }), [
        displayTooltips,
        data.description,
        isDisabled,
        executionStatus,
        suggestionType,
        resourceIcon,
        handleConfigurations,
        toolbarConfig,
        breakpointAdornment,
        statusAdornment,
        suggestionAdornment,
        guardrailsAdornment
    ]);
    return /*#__PURE__*/ jsx(BaseNodeOverrideConfigProvider, {
        value: baseNodeConfig,
        children: /*#__PURE__*/ jsx(BaseNode, {
            ...nodeProps,
            type: getResourceNodeType(),
            data: {
                ...data,
                display: {
                    iconBackground: 'var(--canvas-background-secondary)',
                    label: data.name,
                    subLabel: data.originalName,
                    shape: 'circle'
                }
            },
            id: id,
            selected: selected,
            draggable: false,
            selectable: true,
            deletable: !isSuggestion
        })
    });
});
export { ResourceNode };
