import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { getFieldHistory } from "../editor/services/editService";
import { useEffect, useState } from "react";
import { useEditContext } from "./client/editContext";
import { formatDate } from "./utils";
import { SimpleTable } from "./ui/SimpleTable";
import { Brush, GalleryVertical, History, Undo2, User, Layers, ArrowRight } from "lucide-react";
import { Checkbox } from "../components/ui/checkbox";
import { cn } from "../lib/utils";
import { DiffView } from "./reviews/DiffView";
import { Tooltip, TooltipContent, TooltipTrigger } from "../components/ui/tooltip";
function isTextLikeFieldType(type) {
    return (type === "raw" ||
        type === "single-line text" ||
        type === "multi-line text" ||
        type === "rich text");
}
function fieldHistoryEntriesEqual(a, b) {
    return (a.date === b.date &&
        a.version === b.version &&
        a.rawValue === b.rawValue &&
        a.user === b.user &&
        a.agentId === b.agentId &&
        a.isBaseline === b.isBaseline &&
        a.ai === b.ai &&
        a.undone === b.undone);
}
function isCurrentHistoryEntry(item, fieldHistory) {
    if (item.isBaseline) {
        return false;
    }
    const latestEntry = fieldHistory.find((entry) => !entry.isBaseline) ?? fieldHistory[0];
    return latestEntry ? fieldHistoryEntriesEqual(item, latestEntry) : false;
}
function areAdjacentInItemHistory(newerEntry, olderEntry) {
    if (newerEntry.itemHistoryIndex == null ||
        olderEntry.itemHistoryIndex == null) {
        return false;
    }
    return olderEntry.itemHistoryIndex === newerEntry.itemHistoryIndex + 1;
}
export function FieldHistory({ field, onRevert, configuration, showRawValue: initialShowRawValue, }) {
    const [fieldHistory, setFieldHistory] = useState([]);
    const [selectedEntry, setSelectedEntry] = useState();
    const [showRawValue, setShowRawValue] = useState(initialShowRawValue);
    const [viewMode, setViewMode] = useState("plain");
    const [ignoreFormatting, setIgnoreFormatting] = useState(false);
    const [clipUnchanged, setClipUnchanged] = useState(true);
    const editContext = useEditContext();
    if (!editContext) {
        return null;
    }
    useEffect(() => {
        getFieldHistory(field.descriptor.item, field.id).then((result) => {
            const items = result.data ?? [];
            // Collapse rapid successive edits (e.g. typing) into a single row for stability.
            const sorted = [...items].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
            const collapsed = [];
            const WINDOW_MS = 60_000;
            for (const entry of sorted) {
                const last = collapsed[collapsed.length - 1];
                if (!last) {
                    collapsed.push(entry);
                    continue;
                }
                const sameUser = last.user === entry.user &&
                    last.agentId === entry.agentId &&
                    last.isBaseline === entry.isBaseline &&
                    last.ai === entry.ai &&
                    last.version === entry.version &&
                    last.undone === entry.undone;
                const closeInTime = Math.abs(new Date(last.date).getTime() - new Date(entry.date).getTime()) <
                    WINDOW_MS;
                const adjacentInItemHistory = areAdjacentInItemHistory(last, entry);
                if (sameUser && closeInTime && adjacentInItemHistory) {
                    continue;
                }
                collapsed.push(entry);
            }
            setFieldHistory(collapsed);
            setSelectedEntry(collapsed[0]);
        });
    }, [field]);
    const effectiveFieldType = showRawValue ? "raw" : field.type;
    const isTextLike = isTextLikeFieldType(effectiveFieldType);
    const getHistoryEntryUserLabel = (entry) => {
        if (entry.isBaseline) {
            return "Previous value";
        }
        if (entry.agentId) {
            return entry.agentId;
        }
        return entry.user;
    };
    const renderFieldEditor = () => {
        if (!selectedEntry)
            return null;
        const previewKey = `${selectedEntry.date}:${selectedEntry.version}:${selectedEntry.isBaseline ? "baseline" : "entry"}`;
        const displayField = {
            ...field,
            value: selectedEntry.value,
            rawValue: selectedEntry.rawValue,
            isHistoric: true,
        };
        const fieldType = showRawValue ? "raw" : field.type;
        const typeConfig = configuration.fieldTypes[fieldType] ??
            configuration.fieldTypes["single-line text"];
        if (!typeConfig)
            return null;
        const currentRaw = field.rawValue ?? "";
        const historicRaw = selectedEntry.rawValue ?? "";
        return (_jsxs("div", { className: "flex flex-col h-full", children: [_jsxs("div", { className: "mb-3 flex shrink-0 items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: "bg-theme-secondary-light/30 p-1.5 rounded-md", children: _jsx(History, { size: 14, className: "text-theme-secondary" }) }), _jsx("span", { className: "text-xs font-semibold text-gray-700", children: "Historic Value Preview" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [isTextLike && (_jsxs("div", { className: "flex items-center bg-gray-100 rounded-lg p-0.5", children: [_jsx("button", { onClick: () => setViewMode("plain"), className: cn("px-2 py-1 text-[10px] font-medium rounded-md transition-all", viewMode === "plain" ? "bg-white text-theme-secondary shadow-sm" : "text-gray-500 hover:text-gray-700"), children: "Plain" }), _jsx("button", { onClick: () => setViewMode("diff"), className: cn("px-2 py-1 text-[10px] font-medium rounded-md transition-all", viewMode === "diff" ? "bg-white text-theme-secondary shadow-sm" : "text-gray-500 hover:text-gray-700"), children: "Diff" })] })), _jsxs("div", { className: "flex items-center gap-1.5 ml-1 border-l pl-3", children: [_jsx(Checkbox, { id: "show-raw", className: "size-3.5 border-gray-300 data-[state=checked]:bg-theme-secondary data-[state=checked]:border-theme-secondary", checked: showRawValue, onCheckedChange: (checked) => setShowRawValue(!!checked) }), _jsx("label", { htmlFor: "show-raw", className: "cursor-pointer text-[10px] font-medium text-gray-500 hover:text-gray-700 select-none", children: "Raw" })] })] })] }), _jsx("div", { className: "flex-1 min-h-0 flex flex-col", children: viewMode === "diff" && isTextLike ? (_jsxs("div", { className: "flex flex-col h-full gap-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { onClick: () => setIgnoreFormatting((prev) => !prev), className: cn("p-1.5 rounded-md border transition-all", ignoreFormatting ? "bg-theme-secondary-light/20 border-theme-secondary/30 text-theme-secondary" : "bg-white border-gray-200 text-gray-400 hover:border-gray-300 hover:text-gray-600"), children: _jsx(Brush, { size: 14, strokeWidth: 1.5 }) }) }), _jsx(TooltipContent, { children: "Ignore Formatting" })] }), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { onClick: () => setClipUnchanged((prev) => !prev), className: cn("p-1.5 rounded-md border transition-all", clipUnchanged ? "bg-theme-secondary-light/20 border-theme-secondary/30 text-theme-secondary" : "bg-white border-gray-200 text-gray-400 hover:border-gray-300 hover:text-gray-600"), children: _jsx(GalleryVertical, { size: 14, strokeWidth: 1.5 }) }) }), _jsx(TooltipContent, { children: "Clip Unchanged" })] })] }), _jsxs("div", { className: "flex-1 min-h-0 overflow-auto rounded-xl border border-gray-100 bg-gray-50/50 p-4", children: [_jsxs("div", { className: "mb-3 flex items-center gap-2", children: [_jsx("span", { className: "text-[10px] font-bold uppercase tracking-wider text-gray-400", children: "Current" }), _jsx(ArrowRight, { size: 10, className: "text-gray-300" }), _jsx("span", { className: "text-[10px] font-bold uppercase tracking-wider text-theme-secondary", children: "Historic snapshot" })] }), _jsx("div", { className: "text-xs leading-relaxed font-mono", children: _jsx(DiffView, { oldText: currentRaw, newText: historicRaw, ignoreFormatting: ignoreFormatting, clipUnchanged: clipUnchanged, clipThreshold: 50, clipContext: 10 }) })] })] })) : (_jsx("div", { className: "flex-1 min-h-0 overflow-auto rounded-xl border border-gray-100 bg-white p-4 shadow-sm", children: _jsx(typeConfig.editor, { field: displayField, readOnly: true, isFocusedField: false, updateFieldValue: () => { }, tabIndex: undefined }, previewKey) })) })] }));
    };
    if (fieldHistory.length === 0)
        return (_jsx("div", { "data-testid": "field-history", className: "h-[500px] flex items-center justify-center bg-gray-50/30 rounded-xl border border-dashed border-gray-200", children: _jsxs("div", { className: "flex flex-col items-center gap-2", children: [_jsx(History, { size: 32, className: "text-gray-300" }), _jsx("div", { className: "text-sm font-medium text-gray-400", children: "No history available" })] }) }));
    return (_jsxs("div", { "data-testid": "field-history", className: "flex flex-col h-[600px] bg-white", children: [_jsx("div", { className: "shrink-0 px-4 py-3 border-b border-gray-100 flex items-center justify-between", children: _jsxs("div", { className: "flex items-center gap-2.5", children: [_jsx("div", { className: "bg-theme-secondary p-1.5 rounded-lg shadow-sm shadow-theme-secondary/20", children: _jsx(History, { size: 16, className: "text-white" }) }), _jsxs("div", { children: [_jsx("h3", { className: "text-sm font-bold text-gray-900 leading-none mb-1", children: "Field History" }), _jsx("p", { className: "text-[10px] text-gray-500 font-medium", children: field.displayName || field.name || "Unknown Field" })] })] }) }), _jsxs("div", { className: "flex min-h-0 flex-1", children: [_jsx("div", { className: "flex min-w-0 w-[45%] flex-col border-r border-gray-100", children: _jsx("div", { className: "min-h-0 flex-1 overflow-auto", children: _jsx(SimpleTable, { items: fieldHistory, onRowClick: ({ item }) => setSelectedEntry(item), "data-testid": "field-history-table", rowClassName: (x) => cn("group transition-colors", x.undone ? "opacity-40" : "", selectedEntry && fieldHistoryEntriesEqual(x, selectedEntry)
                                    ? "bg-theme-secondary-light/20"
                                    : "hover:bg-gray-50/80"), columns: [
                                    {
                                        header: _jsx("span", { className: "text-[10px] uppercase tracking-wider text-gray-400 font-bold px-2", children: "Entry" }),
                                        body: (x) => (_jsxs("div", { className: "flex flex-col gap-1 px-2 py-1", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: "text-xs font-bold text-gray-700", children: formatDate(new Date(x.date)) }), isCurrentHistoryEntry(x, fieldHistory) && (_jsx("span", { className: "px-1.5 py-0.5 rounded-full bg-green-100 text-green-700 text-[9px] font-bold uppercase tracking-tight", children: "Current" }))] }), _jsxs("div", { className: "flex items-center gap-3", children: [_jsxs("div", { className: "flex items-center gap-1 text-[10px] text-gray-500 font-medium", children: [_jsx(User, { size: 10, className: "text-gray-400" }), _jsx("span", { children: getHistoryEntryUserLabel(x) })] }), _jsxs("div", { className: "flex items-center gap-1 text-[10px] text-gray-500 font-medium", children: [_jsx(Layers, { size: 10, className: "text-gray-400" }), _jsxs("span", { children: ["v", x.version] })] })] })] }))
                                    },
                                    {
                                        header: _jsx("span", { className: "text-[10px] uppercase tracking-wider text-gray-400 font-bold text-center block", children: "Action" }),
                                        className: "w-16 text-center",
                                        body: (x) => !isCurrentHistoryEntry(x, fieldHistory) && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "Revert", onClick: async (ev) => {
                                                            ev.stopPropagation();
                                                            await editContext.operations.editField({
                                                                field: field.descriptor,
                                                                rawValue: x.rawValue,
                                                                refresh: "immediate",
                                                            });
                                                            onRevert?.();
                                                        }, className: "p-2 rounded-full text-gray-400 hover:text-theme-secondary hover:bg-theme-secondary-light/30 transition-all", children: _jsx(Undo2, { size: 16 }) }) }), _jsx(TooltipContent, { children: "Revert to this version" })] })),
                                    },
                                ] }) }) }), _jsx("div", { className: "flex min-w-0 flex-1 flex-col bg-gray-50/30 p-4", children: renderFieldEditor() })] })] }));
}
//# sourceMappingURL=FieldHistory.js.map