import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { useEditContext } from "../../client/editContext";
import { SimpleIconButton } from "../../ui/SimpleIconButton";
import { getUndoCommand, getRedoCommand } from "../../commands/undo";
import { ChevronDown, History } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger, } from "../../../components/ui/popover";
import { Button } from "../../../components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../../components/ui/tooltip";
import { cn } from "../../../lib/utils";
import { OperationItem } from "../../sidebar/OperationItem";
const EMPTY_EDIT_HISTORY = [];
export function UndoRedoControls() {
    const editContext = useEditContext();
    const [historyOpen, setHistoryOpen] = useState(false);
    const editHistory = editContext?.editHistory ?? EMPTY_EDIT_HISTORY;
    const hasEditContext = Boolean(editContext);
    const showOnlyMyChanges = editContext?.showOnlyMyChanges ?? false;
    const sessionId = editContext?.sessionId;
    const currentItem = editContext?.item?.descriptor;
    const currentItemId = currentItem?.id;
    const currentItemLanguage = currentItem?.language;
    const currentItemVersion = currentItem?.version;
    const historyMode = editContext?.historyMode;
    // Filter operations based on historyMode and showOnlyMyChanges
    const filterOperation = useMemo(() => {
        if (!hasEditContext)
            return () => false;
        return (op) => {
            // Session filter (showOnlyMyChanges)
            if (showOnlyMyChanges && op.sessionId !== sessionId) {
                return false;
            }
            // Page-centric filter: only show operations for current item and language (any version)
            // EXCEPTION: delete-items operations are always shown because after deleting an item,
            // the user navigates to parent but should still be able to undo the deletion
            if (historyMode === "page-centric" &&
                currentItemId &&
                op.type !== "delete-items") {
                if (!op.mainItem ||
                    op.mainItem.id !== currentItemId ||
                    op.mainItem.language !== currentItemLanguage) {
                    return false;
                }
            }
            // Current-version filter: only show operations for current item and version
            if (historyMode === "current-version" && currentItemId) {
                if (!op.mainItem ||
                    op.mainItem.id !== currentItemId ||
                    op.mainItem.version !== currentItemVersion) {
                    return false;
                }
            }
            return true;
        };
    }, [
        hasEditContext,
        showOnlyMyChanges,
        sessionId,
        historyMode,
        currentItemId,
        currentItemLanguage,
        currentItemVersion,
    ]);
    // Get the next undoable operation (first operation where canUndo is true)
    const nextUndoOperation = useMemo(() => {
        if (!hasEditContext)
            return undefined;
        const undoableOps = editHistory.filter((x) => x.canUndo);
        const filteredOps = undoableOps.filter(filterOperation);
        const result = filteredOps[0];
        return result;
    }, [editHistory, filterOperation, hasEditContext]);
    // Get the next redoable operation (last operation where canRedo is true)
    const nextRedoOperation = useMemo(() => {
        if (!hasEditContext)
            return undefined;
        const result = [...editHistory]
            .reverse()
            .find((x) => x.canRedo && filterOperation(x));
        return result;
    }, [editHistory, filterOperation, hasEditContext]);
    const historyOperations = useMemo(() => {
        if (!hasEditContext)
            return [];
        return editHistory.filter(filterOperation);
    }, [editHistory, filterOperation, hasEditContext]);
    if (!editContext)
        return null;
    const undoCommand = getUndoCommand();
    const redoCommand = getRedoCommand();
    // Build dynamic tooltip labels
    const undoLabel = nextUndoOperation
        ? `Undo: ${nextUndoOperation.title}`
        : "Undo";
    const redoLabel = nextRedoOperation
        ? `Redo: ${nextRedoOperation.title}`
        : "Redo";
    const handleOpenHistorySidepanel = () => {
        editContext.openSidebar("history");
        setHistoryOpen(false);
    };
    return (_jsxs("div", { className: "group/undo-redo flex shrink-0 items-center gap-0.5", children: [_jsx(SimpleIconButton, { onClick: async (ev) => {
                    // Pass the operation ID from current React state to avoid stale ref issues
                    // Await to ensure the operation completes before the click handler returns
                    await editContext.executeCommand({
                        command: undoCommand,
                        event: ev,
                        data: { operationId: nextUndoOperation?.id },
                    });
                }, icon: undoCommand.icon, label: undoLabel, size: "large", "data-testid": "toolbar-undo-button", disabled: editContext.isCommandDisabled({ command: undoCommand }) }), _jsx(SimpleIconButton, { onClick: async (ev) => {
                    // Pass the operation ID from current React state to avoid stale ref issues
                    // Await to ensure the operation completes before the click handler returns
                    await editContext.executeCommand({
                        command: redoCommand,
                        event: ev,
                        data: { operationId: nextRedoOperation?.id },
                    });
                }, icon: redoCommand.icon, label: redoLabel, size: "large", "data-testid": "toolbar-redo-button", disabled: editContext.isCommandDisabled({ command: redoCommand }) }), _jsxs(Popover, { open: historyOpen, onOpenChange: setHistoryOpen, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "Open edit history", "data-testid": "toolbar-edit-history-trigger", className: cn("text-neutral-grey-50 hover:border-neutral-grey-10 hover:bg-neutral-grey-5 hover:text-neutral-grey-100 inline-flex h-7 w-4 shrink-0 items-center justify-center rounded-[4px] border border-transparent opacity-0 transition-all group-hover/undo-redo:opacity-100 focus-visible:opacity-100", historyOpen &&
                                            "bg-neutral-grey-5 text-neutral-grey-100 opacity-100"), children: _jsx(ChevronDown, { className: "h-3 w-3", strokeWidth: 1 }) }) }) }), _jsx(TooltipContent, { side: "bottom", children: "Edit history" })] }), _jsxs(PopoverContent, { align: "start", side: "bottom", sideOffset: 6, className: "w-[420px] max-w-[90vw] p-0", "data-testid": "toolbar-edit-history-popover", children: [_jsxs("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(History, { className: "text-neutral-grey-50 h-3.5 w-3.5 shrink-0", strokeWidth: 1 }), _jsx("span", { className: "text-neutral-grey-100 truncate text-xs font-medium", children: "Edit history" })] }), _jsx("span", { className: "text-neutral-grey-50 shrink-0 text-[10px]", children: historyOperations.length })] }), _jsx("div", { className: "max-h-[60vh] overflow-y-auto", children: historyOperations.length > 0 ? (historyOperations.map((operation, index) => (_jsx(OperationItem, { operation: operation, index: index, showUserName: !editContext.showOnlyMyChanges, showDescription: false, hidePath: editContext.historyMode !== "global", showLanguage: editContext.historyMode === "global" }, operation.id || index)))) : (_jsx("div", { className: "text-neutral-grey-50 p-4 text-center text-xs", children: "No edit history available" })) }), _jsx("div", { className: "border-border-default flex justify-start border-t p-2", children: _jsx(Button, { type: "button", variant: "ghost", size: "xs", onClick: handleOpenHistorySidepanel, "data-testid": "toolbar-edit-history-open-sidepanel-button", children: "Open history sidepanel" }) })] })] })] }));
}
//# sourceMappingURL=UndoRedoControls.js.map