import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState, } from "react";
import { FileCode2, Plus, RefreshCw, ShieldAlert } from "lucide-react";
import { DeleteIcon } from "../../../components/ui/delete-icon";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { SearchInput } from "../../../components/SearchInput";
import { cn } from "../../../lib/utils";
import { useEditContext } from "../../client/editContext";
import { Splitter } from "../../ui/Splitter";
import { updateAgentContext } from "../../services/agentService";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { JavaScriptToolConfigPanel } from "./JavaScriptToolConfigPanel";
import { JavaScriptToolAgentPanel } from "./JavaScriptToolAgentPanel";
import { CreateJavaScriptToolDialog } from "./CreateJavaScriptToolDialog";
import { useRequiredSettingsHeaderActions } from "../SettingsHeaderActionsContext";
const JAVA_SCRIPT_TOOL_ROOT_PATHS = [
    "/sitecore/system/parhelia/settings/ai tools/scripts",
];
const JAVA_SCRIPT_TOOL_EXTERNAL_REFRESH_DEBOUNCE_MS = 350;
function isJavaScriptToolItemChange(changes, selectedToolId) {
    const normalizedSelectedToolId = selectedToolId?.toLowerCase() ?? null;
    return changes.some((change) => {
        const itemId = change.item?.id?.trim().toLowerCase();
        if (normalizedSelectedToolId && itemId === normalizedSelectedToolId) {
            return false;
        }
        const path = change.item?.path?.trim().toLowerCase();
        if (path &&
            JAVA_SCRIPT_TOOL_ROOT_PATHS.some((root) => path.startsWith(root))) {
            return true;
        }
        return false;
    });
}
function buildJavaScriptToolAgentContext(toolId) {
    return {
        activeWorkspace: "settings",
        currentItemId: toolId,
        additionalData: {
            activeWorkspace: "settings",
            javaScriptToolEditor: true,
            javaScriptToolId: toolId,
        },
    };
}
export function JavaScriptToolsPanel() {
    const editContext = useEditContext();
    const setSettingsHeaderActions = useRequiredSettingsHeaderActions();
    const [state, setState] = useState("loading");
    const [tools, setTools] = useState([]);
    const [error, setError] = useState(null);
    const [searchQuery, setSearchQuery] = useState("");
    const [selectedToolId, setSelectedToolId] = useState(null);
    const [showCreateDialog, setShowCreateDialog] = useState(false);
    const [deleting, setDeleting] = useState(false);
    const [agentId, setAgentId] = useState(null);
    const [agentLoading, setAgentLoading] = useState(false);
    const [agentResetting, setAgentResetting] = useState(false);
    const [agentError, setAgentError] = useState(null);
    const selectedToolIdRef = useRef(null);
    const loadToolsRef = useRef(null);
    const externalRefreshTimeoutRef = useRef(null);
    useEffect(() => {
        selectedToolIdRef.current = selectedToolId;
    }, [selectedToolId]);
    const filteredTools = useMemo(() => {
        const query = searchQuery.trim().toLowerCase();
        if (!query) {
            return tools;
        }
        return tools.filter((tool) => {
            return (tool.name.toLowerCase().includes(query) ||
                tool.path.toLowerCase().includes(query) ||
                (tool.description ?? "").toLowerCase().includes(query));
        });
    }, [searchQuery, tools]);
    const selectedTool = useMemo(() => tools.find((tool) => tool.id === selectedToolId) ?? null, [selectedToolId, tools]);
    const loadTools = useCallback(async (preferredToolId) => {
        try {
            setState("loading");
            setError(null);
            const loadedTools = await setupWizardService.getJavaScriptTools();
            setTools(loadedTools);
            const resolvedSelection = loadedTools.find((tool) => tool.id === preferredToolId)?.id ??
                loadedTools.find((tool) => tool.id === selectedToolIdRef.current)?.id ??
                null;
            setSelectedToolId(resolvedSelection);
            setState("success");
        }
        catch (loadError) {
            setState("error");
            setError(loadError instanceof Error
                ? loadError.message
                : "Failed to load JavaScript tools");
            setTools([]);
            setSelectedToolId(null);
        }
    }, []);
    loadToolsRef.current = loadTools;
    useEffect(() => {
        void loadTools();
    }, [loadTools]);
    const syncAgentContext = useCallback(async (nextAgentId, toolId) => {
        try {
            await updateAgentContext(nextAgentId, buildJavaScriptToolAgentContext(toolId));
        }
        catch (contextError) {
            setAgentError(contextError instanceof Error
                ? `Failed to update JavaScript tool assistant context: ${contextError.message}`
                : "Failed to update JavaScript tool assistant context");
        }
    }, []);
    const selectedToolIdentity = selectedTool?.id ?? null;
    useEffect(() => {
        let cancelled = false;
        if (!selectedToolIdentity) {
            setAgentId(null);
            setAgentLoading(false);
            setAgentError(null);
            return () => {
                cancelled = true;
            };
        }
        setAgentLoading(true);
        setAgentId(null);
        setAgentError(null);
        void setupWizardService
            .getJavaScriptToolAgent(selectedToolIdentity)
            .then((session) => {
            if (cancelled)
                return;
            setAgentId(session.agentId);
            setAgentLoading(false);
        })
            .catch((loadError) => {
            if (cancelled)
                return;
            setAgentId(null);
            setAgentLoading(false);
            setAgentError(loadError instanceof Error
                ? loadError.message
                : "Failed to load JavaScript tool assistant");
        });
        return () => {
            cancelled = true;
        };
    }, [selectedToolIdentity]);
    useEffect(() => {
        if (!agentId || agentLoading || !selectedToolIdentity)
            return;
        void syncAgentContext(agentId, selectedToolIdentity);
    }, [agentId, agentLoading, selectedToolIdentity, syncAgentContext]);
    const queueExternalRefresh = useCallback(() => {
        if (externalRefreshTimeoutRef.current !== null) {
            window.clearTimeout(externalRefreshTimeoutRef.current);
        }
        externalRefreshTimeoutRef.current = window.setTimeout(() => {
            externalRefreshTimeoutRef.current = null;
            void loadToolsRef.current?.(selectedToolIdRef.current);
        }, JAVA_SCRIPT_TOOL_EXTERNAL_REFRESH_DEBOUNCE_MS);
    }, []);
    useEffect(() => {
        if (!editContext?.itemsRepository) {
            return;
        }
        return editContext.itemsRepository.subscribeItemsChanged((changes) => {
            if (!isJavaScriptToolItemChange(changes, selectedToolIdRef.current)) {
                return;
            }
            queueExternalRefresh();
        });
    }, [editContext, queueExternalRefresh]);
    useEffect(() => {
        return () => {
            if (externalRefreshTimeoutRef.current !== null) {
                window.clearTimeout(externalRefreshTimeoutRef.current);
            }
        };
    }, []);
    const handleDeleteSelectedTool = useCallback(async () => {
        if (!selectedTool)
            return;
        if (!editContext?.confirm) {
            return;
        }
        editContext.confirm({
            header: "Delete JavaScript Tool",
            message: `Delete JavaScript tool '${selectedTool.name}'? This cannot be undone.`,
            acceptLabel: "Delete",
            showCancel: true,
            accept: async () => {
                try {
                    setDeleting(true);
                    await setupWizardService.deleteJavaScriptTool(selectedTool.id);
                    toast.success(`Deleted '${selectedTool.name}'`);
                    await loadTools();
                }
                catch (deleteError) {
                    const message = deleteError instanceof Error
                        ? deleteError.message
                        : "Failed to delete JavaScript tool";
                    toast.error(message);
                }
                finally {
                    setDeleting(false);
                }
            },
        });
    }, [editContext, loadTools, selectedTool]);
    const handleResetAssistant = useCallback(async () => {
        if (!selectedTool)
            return;
        try {
            setAgentResetting(true);
            setAgentError(null);
            const session = await setupWizardService.resetJavaScriptToolAgent(selectedTool.id);
            setAgentId(session.agentId);
            await syncAgentContext(session.agentId, selectedTool.id);
        }
        catch (resetError) {
            const message = resetError instanceof Error
                ? resetError.message
                : "Failed to restart the JavaScript tool assistant";
            setAgentError(message);
            toast.error(message);
        }
        finally {
            setAgentResetting(false);
        }
    }, [selectedTool, syncAgentContext]);
    const handleCreated = useCallback(async (toolId) => {
        await loadTools(toolId);
        toast.success("JavaScript tool created");
    }, [loadTools]);
    const addToolButton = useMemo(() => (_jsxs(Button, { size: "sm", variant: "default", onClick: () => setShowCreateDialog(true), disabled: state === "loading", title: "Add JavaScript tool", children: [_jsx(Plus, { className: "mr-1 h-4 w-4", strokeWidth: 1 }), "Add tool"] })), [state]);
    // Surface the primary "Add" action in the settings header bar (desktop only;
    // a mobile fallback lives in the panel toolbar below).
    useEffect(() => {
        if (!setSettingsHeaderActions)
            return;
        setSettingsHeaderActions(addToolButton);
        return () => {
            setSettingsHeaderActions(null);
        };
    }, [addToolButton, setSettingsHeaderActions]);
    const toolsListContent = (_jsx(SettingsPanelLayout, { children: _jsxs("div", { className: "overflow-hidden rounded-lg bg-white", children: [_jsxs("div", { className: "shrink-0 px-4 py-3", children: [_jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center", children: [_jsx(SearchInput, { value: searchQuery, onChange: setSearchQuery, placeholder: "Filter by name, path, or description...", className: "w-full" }), _jsx("div", { className: "shrink-0 md:hidden", children: addToolButton })] }), error ? (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red mt-2 rounded border p-2 text-xs whitespace-pre-wrap", children: error })) : null] }), _jsx("div", { className: "px-4 py-3", children: filteredTools.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center px-6 py-12 text-center", children: [_jsx(FileCode2, { className: "text-neutral-grey-50 mb-4 h-10 w-10", strokeWidth: 1 }), _jsx("p", { className: "text-neutral-grey-50 text-sm font-medium", children: tools.length === 0
                                    ? "No JavaScript tools yet"
                                    : "No matching JavaScript tools" }), _jsx("p", { className: "text-neutral-grey-50 mt-1 text-xs", children: tools.length === 0
                                    ? "Create a custom JavaScript tool to expose a hidden script behind a normal tool signature."
                                    : "Try a different search term." })] })) : (_jsx("div", { className: "divide-border-default divide-y", children: filteredTools.map((tool) => {
                            const isSelected = tool.id === selectedToolId;
                            return (_jsxs("button", { type: "button", onClick: () => setSelectedToolId(tool.id), className: cn("group focus-visible:ring-feedback-blue flex w-full cursor-pointer items-center gap-3 px-3 py-3 text-left text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset", isSelected
                                    ? "bg-neutral-grey-5"
                                    : "hover:bg-neutral-grey-5 bg-white"), children: [_jsx(FileCode2, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1 }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [_jsx("span", { className: "text-neutral-grey-100 truncate font-normal", children: tool.name }), tool.needsConfiguration ? (_jsx("span", { className: "bg-feedback-orange-light badge-pad-sm text-feedback-orange shrink-0 rounded text-[10px] font-medium", children: "Needs setup" })) : null] }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: tool.description ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-neutral-grey-50 font-mono", children: tool.path }), _jsx("span", { className: "text-neutral-grey-50 mx-1.5", children: "\u00B7" }), _jsx("span", { children: tool.description })] })) : (_jsx("span", { className: "text-neutral-grey-50 font-mono", children: tool.path })) })] })] }, tool.id));
                        }) })) })] }) }));
    const detailsContent = (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsx("div", { className: "flex min-h-[360px] flex-col overflow-hidden rounded-lg bg-white xl:min-h-0", children: selectedTool ? (_jsx("div", { className: "min-h-0 flex-1", children: _jsx(JavaScriptToolConfigPanel, { itemId: selectedTool.id, title: selectedTool.name, actions: _jsxs(Button, { variant: "outline", size: "sm", onClick: () => void handleDeleteSelectedTool(), disabled: deleting, title: "Delete selected JavaScript tool", children: [deleting ? (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1 })) : (_jsx(DeleteIcon, { size: "lg" })), "Delete Tool"] }) }) })) : (_jsxs("div", { className: "flex h-full min-h-[360px] flex-col items-center justify-center gap-3 p-8 text-center xl:min-h-0", children: [_jsx(FileCode2, { className: "text-neutral-grey-50 h-10 w-10", strokeWidth: 1 }), _jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-neutral-grey-100 text-sm font-medium", children: "Select a JavaScript tool" }), _jsx("div", { className: "text-neutral-grey-50 text-xs", children: "Choose a tool from the list to edit its schema, script, and approval logic." })] })] })) }) }));
    const agentContent = selectedTool ? (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsx("div", { className: "flex min-h-[360px] flex-col overflow-hidden rounded-lg bg-white xl:min-h-0", children: _jsx("div", { className: "min-h-0 flex-1", children: _jsx(JavaScriptToolAgentPanel, { toolName: selectedTool.name, agentId: agentId, loading: agentLoading, resetting: agentResetting, error: agentError, onStartOver: handleResetAssistant, headerStart: selectedTool.hasApprovalScript ? (_jsx("div", { className: "bg-neutral-grey-5 text-neutral-grey-50 rounded-full p-1", children: _jsx(ShieldAlert, { className: "h-3.5 w-3.5", strokeWidth: 1 }) })) : null }) }) }) })) : null;
    const panels = selectedTool
        ? [
            {
                name: "javascript-tools-list",
                defaultSize: 320,
                content: toolsListContent,
                className: "overflow-hidden",
            },
            {
                name: "javascript-tools-details",
                defaultSize: 520,
                content: detailsContent,
                className: "overflow-hidden",
            },
            {
                name: "javascript-tools-agent",
                defaultSize: 560,
                content: agentContent,
                className: "overflow-hidden",
            },
        ]
        : [
            {
                name: "javascript-tools-list",
                defaultSize: 320,
                content: toolsListContent,
                className: "overflow-hidden",
            },
            {
                name: "javascript-tools-details",
                defaultSize: 520,
                content: detailsContent,
                className: "overflow-hidden",
            },
        ];
    return (_jsxs(_Fragment, { children: [_jsx(Splitter, { panels: panels, localStorageKey: "javascript-tools-panel-splitter-v1", direction: "horizontal", className: "h-full", splitterClassName: "bg-neutral-grey-10 hover:bg-neutral-grey-10 w-[6px]" }), _jsx(CreateJavaScriptToolDialog, { open: showCreateDialog, onOpenChange: setShowCreateDialog, onCreated: handleCreated })] }));
}
export default JavaScriptToolsPanel;
//# sourceMappingURL=JavaScriptToolsPanel.js.map