'use client'; import { useState } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { RotateCcw, Clock } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { apiFetch } from '@/lib/api/client'; import { useConfirmation } from '@/hooks/use-confirmation'; interface TemplateVersion { version: number; content: Record; changedBy: string | null; changedAt: string; auditLogId: string; } interface TemplateVersionHistoryProps { templateId: string; currentVersion: number; onRollback: () => void; } export function TemplateVersionHistory({ templateId, currentVersion, onRollback, }: TemplateVersionHistoryProps) { const queryClient = useQueryClient(); const { confirm, dialog: confirmDialog } = useConfirmation(); const queryKey = ['admin', 'template-versions', templateId] as const; const [rollingBack, setRollingBack] = useState(null); const [error, setError] = useState(null); const { data: versions = [], isLoading: loading, error: queryError, } = useQuery({ queryKey, queryFn: () => apiFetch<{ data: TemplateVersion[] }>(`/api/v1/admin/templates/${templateId}/versions`).then( (r) => r.data, ), }); const fetchVersions = () => queryClient.invalidateQueries({ queryKey }); const effectiveError = error ?? (queryError instanceof Error ? queryError.message : null); async function handleRollback(version: number) { const ok = await confirm({ title: `Roll back to version ${version}`, description: `This will create a new version ${currentVersion + 1}.`, confirmLabel: 'Restore', }); if (!ok) return; setRollingBack(version); setError(null); try { await apiFetch(`/api/v1/admin/templates/${templateId}/rollback`, { method: 'POST', body: { version }, }); onRollback(); await fetchVersions(); } catch (err: unknown) { setError(err instanceof Error ? err.message : 'Rollback failed'); } finally { setRollingBack(null); } } if (loading) { return (
Loading version history…
); } if (versions.length === 0) { return (

No previous versions found. Versions are saved whenever you update the template content.

); } return (
{effectiveError && (

{effectiveError}

)}

Current version: v{currentVersion}. Click Restore to roll back to a previous version (creates a new version).

{versions.map((v) => (
v{v.version} Version {v.version}

Saved{' '} {new Date(v.changedAt).toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', })} {v.changedBy ? ` by ${v.changedBy}` : ''}

))}
{confirmDialog}
); }