'use client'; import { useState, useEffect, useCallback } from 'react'; import { RotateCcw, Clock } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { apiFetch } from '@/lib/api/client'; 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 [versions, setVersions] = useState([]); const [loading, setLoading] = useState(true); const [rollingBack, setRollingBack] = useState(null); const [error, setError] = useState(null); const fetchVersions = useCallback(async () => { setLoading(true); setError(null); try { const res = await apiFetch<{ data: TemplateVersion[] }>( `/api/v1/admin/templates/${templateId}/versions`, ); setVersions(res.data); } catch (err: unknown) { setError(err instanceof Error ? err.message : 'Failed to load versions'); } finally { setLoading(false); } }, [templateId]); useEffect(() => { void fetchVersions(); }, [fetchVersions]); async function handleRollback(version: number) { if (!confirm(`Roll back to version ${version}? This will create a new version ${currentVersion + 1}.`)) 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 (
{error && (

{error}

)}

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}` : ''}

))}
); }