import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { ArrowLeft, FileText, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "../../../../components/ui/button";
import ContentTree from "../../../ContentTree";
import { useEditContext } from "../../../client/editContext";
import { updateAgentContext, } from "../../../services/agentService";
import { getAgentContextItemKey } from "../agentContextMerge";
const CONTENT_ROOT_ID = "0de95ae4-41ab-4d01-9eb0-67441b7c2450";
const CONTEXT_ITEM_ROOT_IDS = [CONTENT_ROOT_ID];
function normalizeLanguage(language) {
    if (!language || language === "*" || language === "mixed")
        return "en";
    return language;
}
function toContextItem(item, fallbackLanguage) {
    const contextItem = {
        id: item.id,
        language: normalizeLanguage(item.language || fallbackLanguage),
        version: item.version || 1,
    };
    const name = item.displayName?.trim() || item.name;
    if (name)
        contextItem.name = name;
    if (item.path || item.idPath)
        contextItem.path = item.path || item.idPath;
    return contextItem;
}
export function AgentContextItemPicker({ agent, agentMetadata, setAgentMetadata, setAgent, onBack, onDone, }) {
    const editContext = useEditContext();
    const language = normalizeLanguage(editContext?.item?.language ?? editContext?.currentItemDescriptor?.language);
    const existingItems = agentMetadata?.items ?? [];
    const [selectedItems, setSelectedItems] = useState([]);
    const [saving, setSaving] = useState(false);
    const existingKeys = useMemo(() => {
        return new Set(existingItems.map((item) => getAgentContextItemKey(item)));
    }, [existingItems]);
    const itemsToAdd = useMemo(() => {
        const seen = new Set(existingKeys);
        return selectedItems
            .map((item) => toContextItem(item, language))
            .filter((item) => {
            const key = getAgentContextItemKey(item);
            if (!key || seen.has(key))
                return false;
            seen.add(key);
            return true;
        });
    }, [existingKeys, language, selectedItems]);
    const selectedItemIds = selectedItems.map((item) => item.id);
    const selectedCount = selectedItems.length;
    const handleAddSelected = async () => {
        if (!agent?.id || itemsToAdd.length === 0 || saving)
            return;
        const current = agentMetadata || {};
        const next = {
            ...current,
            items: [...(current.items ?? []), ...itemsToAdd],
        };
        setSaving(true);
        try {
            if (agent.status !== "new") {
                await updateAgentContext(agent.id, next);
            }
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
            toast.success(`Added ${itemsToAdd.length} item${itemsToAdd.length === 1 ? "" : "s"} to context`);
            onDone();
        }
        catch (error) {
            console.error("Failed to add items to agent context", error);
            toast.error("Failed to add items to context");
        }
        finally {
            setSaving(false);
        }
    };
    return (_jsxs("div", { className: "flex h-[420px] max-h-[70vh] flex-col bg-white", children: [_jsx("div", { className: "border-border-default flex items-center justify-between gap-2 border-b px-3 py-2", children: _jsxs("div", { className: "flex min-w-0 items-center gap-1.5", children: [_jsx(Button, { type: "button", size: "iconXs", variant: "ghost", "aria-label": "Back", title: "Back", className: "h-6 w-6 shrink-0", onClick: onBack, children: _jsx(ArrowLeft, { className: "size-3.5", strokeWidth: 1.5 }) }), _jsx(FileText, { className: "text-neutral-grey-50 h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 }), _jsx("span", { className: "text-neutral-grey-100 truncate text-xs font-medium", children: "Add items to context" })] }) }), _jsx("div", { className: "min-h-0 flex-1 overflow-auto p-2", children: _jsx(ContentTree, { language: language, rootItemIds: CONTEXT_ITEM_ROOT_IDS, hideRootNodes: true, includeItemPath: true, selectionMode: "multiple", multiSelectRequiresModifier: false, showCheckboxes: true, selectedItemIds: selectedItemIds, onSelectionChange: (items) => setSelectedItems(items) }) }), _jsxs("div", { className: "border-border-default flex items-center justify-between gap-2 border-t px-3 py-2", children: [_jsxs("span", { className: "text-neutral-grey-50 text-xs", children: [selectedCount, " selected"] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Button, { type: "button", size: "xs", variant: "ghost", onClick: onDone, children: "Cancel" }), _jsxs(Button, { type: "button", size: "xs", disabled: itemsToAdd.length === 0 || saving, onClick: () => void handleAddSelected(), children: [saving ? _jsx(Loader2, { className: "size-3 animate-spin" }) : null, "Add selected"] })] })] })] }));
}
//# sourceMappingURL=AgentContextItemPicker.js.map