import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useCallback, useMemo } from "react";
import { ChevronDown, ChevronUp, History, RotateCcw, CheckSquare, Square } from "lucide-react";
import { getAgentHistory } from "../services/editService";
import { OperationItem } from "../sidebar/OperationItem";
import { useEditContext } from "../client/editContext";
export function AgentEditOperationsPanel({ agentId, onHasContent, }) {
    const [isExpanded, setIsExpanded] = useState(false);
    const [agentOperations, setAgentOperations] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
    const [selectedIds, setSelectedIds] = useState(new Set());
    const editContext = useEditContext();
    useEffect(() => {
        if (hasLoadedOnce && onHasContent) {
            onHasContent(agentOperations.length > 0);
        }
    }, [hasLoadedOnce, agentOperations.length, onHasContent]);
    // Fetch edit operations from backend by agentId
    const fetchOperations = useCallback(async () => {
        if (!agentId) {
            setAgentOperations([]);
            setSelectedIds(new Set());
            setIsLoading(false);
            setHasLoadedOnce(true);
            return;
        }
        setIsLoading(true);
        try {
            const result = await getAgentHistory(agentId, 1000);
            if (result.type === "success" && result.data) {
                const operations = result.data;
                setAgentOperations(operations);
                // Cleanup selection if IDs are no longer in history or already undone
                setSelectedIds((prev) => {
                    const next = new Set();
                    prev.forEach((id) => {
                        const op = operations.find((o) => o.id === id);
                        if (op && !op.undone) {
                            next.add(id);
                        }
                    });
                    return next;
                });
            }
        }
        catch (error) {
            console.error("Failed to fetch agent operations:", error);
        }
        finally {
            setIsLoading(false);
            setHasLoadedOnce(true);
        }
    }, [agentId]);
    // Initial load
    useEffect(() => {
        fetchOperations();
    }, [fetchOperations]);
    // Listen to WebSocket messages for edit operations from this agent
    useEffect(() => {
        if (!agentId || !editContext?.addSocketMessageListener) {
            return;
        }
        const handleMessage = (message) => {
            // Check if this is an edit-operation message from our agent
            if (message.type === "edit-operation") {
                const op = message.payload;
                // Check both op.agentId and op.user?.agentId
                const operationAgentId = op.agentId || op.user?.agentId;
                if (operationAgentId === agentId) {
                    // Reload operations when this agent performs an operation
                    fetchOperations();
                }
            }
        };
        const unsubscribe = editContext.addSocketMessageListener(handleMessage);
        return () => {
            unsubscribe();
        };
    }, [agentId, editContext, fetchOperations]);
    const handleToggleSelection = useCallback((id, selected) => {
        setSelectedIds((prev) => {
            const next = new Set(prev);
            if (selected) {
                next.add(id);
            }
            else {
                next.delete(id);
            }
            return next;
        });
    }, []);
    const undoableOps = useMemo(() => agentOperations.filter((o) => !o.undone && o.undoSupported !== false), [agentOperations]);
    const handleSelectAll = useCallback((e) => {
        e.stopPropagation();
        if (selectedIds.size === undoableOps.length) {
            setSelectedIds(new Set());
        }
        else {
            setSelectedIds(new Set(undoableOps.map((o) => o.id)));
        }
    }, [undoableOps, selectedIds]);
    const handleUndoSelected = useCallback((e) => {
        e.stopPropagation();
        if (selectedIds.size === 0)
            return;
        const performUndo = () => {
            editContext?.operations.undoOperations(Array.from(selectedIds));
            setSelectedIds(new Set());
        };
        // Show confirmation dialog when undoing multiple operations
        if (selectedIds.size > 1) {
            editContext?.confirm({
                header: "Undo Selected Operations",
                message: `Are you sure you want to undo ${selectedIds.size} selected operations?\n\nNote: Undoing selective operations might fail if dependent changes have been made.`,
                acceptLabel: "Undo Selected",
                accept: performUndo,
                showCancel: true,
            });
        }
        else {
            performUndo();
        }
    }, [selectedIds, editContext]);
    const handleUndoAll = useCallback((e) => {
        e.stopPropagation();
        if (undoableOps.length === 0)
            return;
        editContext?.confirm({
            header: "Undo All Actions",
            message: `Are you sure you want to undo all ${undoableOps.length} actions from this agent?`,
            acceptLabel: "Undo All",
            accept: () => {
                editContext?.operations.undoOperations(undoableOps.map(o => o.id));
                setSelectedIds(new Set());
            },
            showCancel: true,
        });
    }, [undoableOps, editContext]);
    // Don't render if no operations (prevents flicker on initial load)
    // Only show panel if we have operations OR if we're refreshing existing operations
    if (agentOperations.length === 0 && (!isLoading || !hasLoadedOnce))
        return null;
    return (_jsxs("div", { className: "border-t border-gray-200 bg-gray-50", children: [_jsxs("div", { onClick: () => setIsExpanded(!isExpanded), className: "flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors hover:bg-gray-100", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(History, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 }), _jsx("span", { className: "text-xs font-normal text-gray-700", children: "Edit History" }), _jsxs("span", { className: "text-xs text-gray-500", children: ["(", agentOperations.length, ")"] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [undoableOps.length > 0 && (_jsxs(_Fragment, { children: [_jsx("button", { onClick: handleSelectAll, className: " hover:bg-gray-200 rounded text-gray-500 transition-colors", title: selectedIds.size === undoableOps.length ? "Deselect All" : "Select All", children: selectedIds.size === undoableOps.length ?
                                            _jsx(CheckSquare, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }) :
                                            _jsx(Square, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }) }), selectedIds.size > 0 ? (_jsxs("button", { onClick: handleUndoSelected, className: "flex items-center gap-1 px-2 bg-theme-secondary-light hover:bg-theme-secondary-light/80 text-theme-secondary rounded text-[10px] font-medium transition-colors", title: `Undo ${selectedIds.size} selected actions`, children: [_jsx(RotateCcw, { className: "h-3 w-3" }), "Undo Selected (", selectedIds.size, ")"] })) : (_jsxs("button", { onClick: handleUndoAll, className: "flex items-center gap-1 px-2  hover:bg-gray-200 text-gray-600 rounded text-[10px] transition-colors", title: "Undo all actions from this agent", children: [_jsx(RotateCcw, { className: "h-3 w-3" }), "Undo All"] }))] })), isExpanded ? (_jsx(ChevronUp, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 })) : (_jsx(ChevronDown, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 }))] })] }), isExpanded && (_jsx("div", { className: "max-h-64 overflow-y-auto", children: agentOperations.map((op, i) => (_jsx(OperationItem, { operation: op, index: i, showUserName: false, showCheckbox: true, selected: selectedIds.has(op.id), onSelect: (selected) => handleToggleSelection(op.id, selected) }, op.id))) }))] }));
}
//# sourceMappingURL=EditOperationsPanel.js.map