"use client"; // components/ReportActions.tsx // Two buttons: "Create PDF" (download) and "Mail PDF" (email). // Used on Company and Director detail pages. import { useState } from "react"; interface Props { type: "company" | "director"; id: string; /** Shown in the mail sent confirmation. */ emailAddress?: string | null; } export default function ReportActions({ type, id, emailAddress }: Props) { const [pdfLoading, setPdfLoading] = useState(false); const [mailLoading, setMailLoading] = useState(false); const [mailResult, setMailResult] = useState<{ ok: boolean; message: string } | null>(null); async function handleDownloadPdf() { setPdfLoading(true); try { const res = await fetch(`/api/report/${type}/${id}/pdf`); if (!res.ok) { const err = await res.json().catch(() => ({ error: "Unknown error" })); alert(`PDF error: ${err.error}`); return; } const blob = await res.blob(); const disposition = res.headers.get("Content-Disposition") ?? ""; const nameMatch = disposition.match(/filename="?([^"]+)"?/); const filename = nameMatch ? nameMatch[1] : `${type}_report.pdf`; const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); } catch (e) { alert(`PDF download failed: ${e instanceof Error ? e.message : String(e)}`); } finally { setPdfLoading(false); } } async function handleMailPdf() { if (!emailAddress) { alert("No email address on file for this " + (type === "company" ? "company." : "director.")); return; } if (!confirm(`Send the ${type} report PDF to ${emailAddress}?`)) return; setMailLoading(true); setMailResult(null); try { const res = await fetch(`/api/report/${type}/${id}/email`, { method: "POST" }); const data = await res.json(); if (res.ok && data.ok) { setMailResult({ ok: true, message: `Sent to ${data.sent_to}` }); } else { setMailResult({ ok: false, message: data.error ?? "Send failed" }); } } catch (e) { setMailResult({ ok: false, message: e instanceof Error ? e.message : String(e), }); } finally { setMailLoading(false); } } return (