'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { X, RotateCcw, Clock, User, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
import { adminPortalContainer } from '../lib/portal-container.js';
function timeAgo(dateStr) {
    const diff = Date.now() - new Date(dateStr).getTime();
    const minutes = Math.floor(diff / 60_000);
    if (minutes < 1)
        return 'just now';
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24)
        return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 30)
        return `${days}d ago`;
    return new Date(dateStr).toLocaleDateString();
}
const CHANGE_TYPE_LABELS = {
    CREATE: { label: 'Created', color: 'bg-success/15 text-success' },
    UPDATE: { label: 'Updated', color: 'bg-primary/15 text-primary' },
    DELETE: { label: 'Deleted', color: 'bg-destructive/15 text-destructive' },
    RESTORE: { label: 'Restored', color: 'bg-accent text-accent-foreground' },
};
export function VersionHistory({ collectionSlug, documentId, open, onClose, onRestore, }) {
    const [versions, setVersions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [restoring, setRestoring] = useState(null);
    useEffect(() => {
        if (open)
            fetchVersions();
    }, [open, collectionSlug, documentId]);
    async function fetchVersions() {
        setLoading(true);
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}/versions?pageSize=50`);
        if (res.data) {
            setVersions(res.data.versions ?? []);
        }
        setLoading(false);
    }
    async function handleRestore(version) {
        setRestoring(version.id);
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}/versions/${version.id}/restore`, { method: 'POST' });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Version restored');
            if (onRestore && version.data) {
                onRestore(version.data);
            }
            fetchVersions();
        }
        setRestoring(null);
    }
    return (_jsx(Dialog.Root, { open: open, onOpenChange: (next) => !next && onClose(), children: _jsxs(Dialog.Portal, { container: adminPortalContainer(), children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-50 bg-black/30" }), _jsxs(Dialog.Content, { "aria-describedby": undefined, className: "bg-card text-card-foreground border-border animate-in slide-in-from-right fixed inset-y-0 right-0 z-50 flex w-full max-w-md flex-col border-l shadow-xl focus:outline-none", children: [_jsxs("div", { className: "border-border flex items-center justify-between border-b px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Clock, { className: "text-muted-foreground h-5 w-5", "aria-hidden": true }), _jsx(Dialog.Title, { className: "text-foreground text-lg font-medium", children: "Version History" })] }), _jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "Close version history", className: "text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring rounded-lg p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none", children: _jsx(X, { className: "h-5 w-5", "aria-hidden": true }) }) })] }), _jsx("div", { className: "flex-1 overflow-y-auto", children: loading ? (_jsx("div", { className: "flex items-center justify-center py-16", children: _jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin", "aria-hidden": true }) })) : versions.length === 0 ? (_jsx("div", { className: "text-muted-foreground py-16 text-center text-sm", children: "No version history available" })) : (_jsx("div", { className: "divide-border divide-y", children: versions.map((version, index) => {
                                    const typeInfo = CHANGE_TYPE_LABELS[version.changeType] ?? {
                                        label: version.changeType,
                                        color: 'bg-muted text-muted-foreground',
                                    };
                                    const isLatest = index === 0;
                                    return (_jsx("div", { className: "hover:bg-accent/50 px-4 py-3 transition-colors", children: _jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "mb-1 flex items-center gap-2", children: [_jsx("span", { className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${typeInfo.color}`, children: typeInfo.label }), isLatest && (_jsx("span", { className: "text-muted-foreground text-xs font-medium", children: "Current" }))] }), _jsxs("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [version.changedBy && (_jsxs("span", { className: "flex items-center gap-1", children: [_jsx(User, { className: "h-3 w-3", "aria-hidden": true }), version.changedBy.name ?? version.changedBy.email ?? 'Unknown'] })), _jsx("span", { title: new Date(version.createdAt).toLocaleString(), children: timeAgo(version.createdAt) })] })] }), !isLatest && (_jsxs("button", { type: "button", onClick: () => handleRestore(version), disabled: restoring === version.id, className: "bg-primary/10 text-primary hover:bg-primary/20 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors disabled:opacity-50", children: [restoring === version.id ? (_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin", "aria-hidden": true })) : (_jsx(RotateCcw, { className: "h-3.5 w-3.5", "aria-hidden": true })), "Restore"] }))] }) }, version.id));
                                }) })) })] })] }) }));
}
//# sourceMappingURL=VersionHistory.js.map