"use client"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { useRef, useState } from "react"; import { previewHistoryRestore, restoreHistory } from "@/actions/history"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogTitle, } from "@/components/ui/dialog"; export function HistoryRestore({ id }: { id: number }) { const t = useTranslations("pages.admin.logs.history"); const router = useRouter(); const [open, setOpen] = useState(false); const pending = useRef<"preview" | "restore" | null>(null); const [busy, setBusy] = useState<"preview" | "restore" | null>(null); const [error, setError] = useState(""); const [preview, setPreview] = useState > | null>(null); async function load() { if (pending.current) return; pending.current = "preview"; setOpen(true); setBusy("preview"); setError(""); setPreview(null); try { setPreview(await previewHistoryRestore(id)); } catch { setError(t("unavailable")); } finally { pending.current = null; setBusy(null); } } async function restore() { if (pending.current || !preview?.canRestore || !preview.changes.length) return; pending.current = "restore"; setBusy("restore"); setError(""); try { const result = await restoreHistory(id); if (!result.ok) { setError(t(result.code)); setPreview(null); return; } setOpen(false); router.refresh(); } catch { setError(t("failed")); } finally { pending.current = null; setBusy(null); } } return ( <> { if (!nextOpen && pending.current === "restore") { details.cancel(); return; } setOpen(nextOpen); }} > {t("title")} {t("description")} {busy && (

{t(busy === "restore" ? "restoring" : "loading")}

)} {error && (

{error}

)} {preview && ( <> {!preview.canRestore && (

{t("conflict")}

)}
{preview.changes.map((change) => (

{t.has(`fields.${change.key}`) ? t(`fields.${change.key}`) : t("field")}

{t("current")}
														{String(change.current ?? "—")}
													
{t("restore")}
														{String(change.restore ?? "—")}
													
))}
)}
); }