import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useEffect, useState } from "react";
import { Brain, Loader2, Pencil, Plus } from "lucide-react";
import { DeleteIcon } from "../../../../components/ui/delete-icon";
import { Button } from "../../../../components/ui/button";
import { Input } from "../../../../components/ui/input";
import { Textarea } from "../../../../components/ui/textarea";
import { useEditContext } from "../../../client/editContext";
import { getAgentMemories, saveAgentMemory, deleteAgentMemory, } from "../../../services/agentService";
/**
 * Viewer/editor for the current user's persistent memory entries of an agent
 * profile. Entries are injected into the agent's system prompt; the agent
 * writes them via the memory-write tool, users manage them here.
 */
export function AgentMemoryPanel({ profileId, headerless, onCountChange, }) {
    const [memories, setMemories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    // Entry id being edited, or "new" while adding
    const [editingId, setEditingId] = useState(null);
    const [draftTitle, setDraftTitle] = useState("");
    const [draftContent, setDraftContent] = useState("");
    const [saving, setSaving] = useState(false);
    const editContext = useEditContext();
    const loadMemories = useCallback(async () => {
        if (!profileId)
            return;
        try {
            setLoading(true);
            const result = await getAgentMemories(profileId);
            if (result.success) {
                setMemories(result.memories ?? []);
                setError(null);
            }
            else {
                setError(result.error || "Failed to load memories");
            }
        }
        catch (err) {
            console.error("Failed to load memories", err);
            setError("Failed to load memories");
        }
        finally {
            setLoading(false);
        }
    }, [profileId]);
    useEffect(() => {
        void loadMemories();
    }, [loadMemories]);
    useEffect(() => {
        onCountChange?.(memories.length);
    }, [memories.length, onCountChange]);
    const startEdit = (entry) => {
        setEditingId(entry.id);
        setDraftTitle(entry.title ?? "");
        setDraftContent(entry.content);
        setError(null);
    };
    const startAdd = () => {
        setEditingId("new");
        setDraftTitle("");
        setDraftContent("");
        setError(null);
    };
    const cancelEdit = () => {
        setEditingId(null);
        setDraftTitle("");
        setDraftContent("");
    };
    const handleSave = async () => {
        if (!draftContent.trim()) {
            setError("Memory content must not be empty.");
            return;
        }
        try {
            setSaving(true);
            const result = await saveAgentMemory({
                id: editingId === "new" ? undefined : (editingId ?? undefined),
                profileId,
                title: draftTitle.trim() || null,
                content: draftContent.trim(),
            });
            if (result.success && result.memory) {
                const saved = result.memory;
                setMemories((prev) => {
                    const existingIndex = prev.findIndex((m) => m.id === saved.id);
                    if (existingIndex === -1) {
                        return [saved, ...prev];
                    }
                    const next = [...prev];
                    next[existingIndex] = saved;
                    return next;
                });
                cancelEdit();
                setError(null);
            }
            else {
                setError(result.error || "Failed to save memory");
            }
        }
        catch (err) {
            console.error("Failed to save memory", err);
            setError("Failed to save memory");
        }
        finally {
            setSaving(false);
        }
    };
    const deleteMemory = async (memoryId) => {
        try {
            const result = await deleteAgentMemory(memoryId);
            if (result.success) {
                setMemories((prev) => prev.filter((m) => m.id !== memoryId));
                if (editingId === memoryId)
                    cancelEdit();
            }
            else {
                setError(result.error || "Failed to delete memory");
            }
        }
        catch (err) {
            console.error("Failed to delete memory", err);
            setError("Failed to delete memory");
        }
    };
    const handleDelete = (memory) => {
        const message = "Delete this memory? This action cannot be undone.";
        if (!editContext) {
            if (typeof window !== "undefined" && window.confirm(message)) {
                void deleteMemory(memory.id);
            }
            return;
        }
        editContext.confirm({
            header: "Delete memory",
            message,
            acceptLabel: "Delete",
            showCancel: true,
            accept: () => {
                void deleteMemory(memory.id);
            },
        });
    };
    const formatDate = (value) => {
        const date = new Date(value);
        return isNaN(date.getTime()) ? "" : date.toLocaleDateString();
    };
    const editorForm = (_jsxs("div", { className: "border-border-default flex flex-col gap-2 rounded-md border bg-white p-2 shadow-sm", "data-testid": "agent-memory-editor", children: [_jsx(Input, { value: draftTitle, onChange: (e) => setDraftTitle(e.target.value), placeholder: "Title (optional)", maxLength: 200, className: "text-xs" }), _jsx(Textarea, { value: draftContent, onChange: (e) => setDraftContent(e.target.value), placeholder: "What should the agent remember?", maxLength: 2000, className: "min-h-16 text-xs" }), _jsxs("div", { className: "flex items-center justify-end gap-1", children: [_jsx(Button, { variant: "ghost", size: "sm", onClick: cancelEdit, disabled: saving, children: "Cancel" }), _jsx(Button, { size: "sm", onClick: () => void handleSave(), disabled: saving, children: saving ? (_jsxs("span", { className: "inline-flex items-center gap-1", children: [_jsx(Loader2, { className: "h-3 w-3 animate-spin", strokeWidth: 1.5 }), "Saving..."] })) : ("Save") })] })] }));
    return (_jsxs("div", { className: headerless ? "px-3 pt-3 pb-3" : "px-4 pb-3", "data-testid": "agent-memory-panel", children: [error && (_jsx("div", { className: "text-feedback-red bg-feedback-red-light mb-2 rounded p-2 text-xs", children: error })), loading ? (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 py-2 text-xs", children: [_jsx(Loader2, { className: "h-3 w-3 animate-spin", strokeWidth: 1.5 }), "Loading memories..."] })) : (_jsxs("div", { className: "flex flex-col gap-2", children: [memories.length === 0 && editingId !== "new" && (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 py-2 text-xs", children: [_jsx(Brain, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }), "No memories stored yet. The agent stores durable facts and preferences here as you work with it."] })), editingId === "new" && editorForm, memories.map((memory) => editingId === memory.id ? (_jsx(React.Fragment, { children: editorForm }, memory.id)) : (_jsxs("div", { className: "border-border-default group grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 rounded-md border bg-white px-2 py-1.5 text-[12px]", "data-testid": "agent-memory-entry", children: [_jsxs("div", { className: "min-w-0", children: [memory.title && (_jsx("div", { className: "text-neutral-grey-100 truncate leading-tight font-medium", children: memory.title })), _jsx("div", { className: "text-neutral-grey-100 leading-snug break-words whitespace-pre-wrap", children: memory.content }), _jsxs("div", { className: "text-neutral-grey-50 mt-0.5 text-[11px] leading-tight", children: ["Updated ", formatDate(memory.updatedDate)] })] }), _jsxs("span", { className: "flex items-center gap-0.5", children: [_jsx("button", { onClick: () => startEdit(memory), className: "hover:bg-neutral-grey-10 rounded p-1", "aria-label": "Edit memory", title: "Edit memory", type: "button", children: _jsx(Pencil, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }) }), _jsx("button", { onClick: () => handleDelete(memory), className: "hover:bg-neutral-grey-10 rounded p-1", "aria-label": "Delete memory", title: "Delete memory", type: "button", children: _jsx(DeleteIcon, { size: "sm" }) })] })] }, memory.id))), editingId === null && (_jsxs("button", { type: "button", onClick: startAdd, className: "text-highlight-100 hover:bg-neutral-grey-5 inline-flex w-fit items-center gap-1 rounded px-1 py-0.5 text-xs", "data-testid": "agent-memory-add", children: [_jsx(Plus, { className: "h-3 w-3", strokeWidth: 1.5 }), "Add memory"] }))] }))] }));
}
//# sourceMappingURL=AgentMemoryPanel.js.map