import { useAuth } from "@clerk/react"; import { exportFromBackend } from "../lib/api"; import { getFlagLabel, getFlagAction, getDeviceDisplay } from "../lib/coverage"; function downloadBlob(blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } export default function CSVExport({ records, batchId }) { const { getToken } = useAuth(); const today = new Date().toISOString().slice(0, 10); const filename = `signal-work-queue-${today}.csv`; const exportCSV = async () => { if (!records || records.length === 0) return; if (batchId) { const token = await getToken().catch(() => null); const blob = await exportFromBackend(records, batchId, token); if (blob) { downloadBlob(blob, filename); return; } } // Fallback: client-side CSV (no batchId or backend unavailable) const headers = [ "Patient ID", "Device", "Payer", "Status", "Priority Score", "Days Until Resupply End", "Recommended Action", "Resupply End Date", "Reason", ]; const rows = records.map((r) => [ r.patient_id, getDeviceDisplay(r.device_type), r.payer, getFlagLabel(r.flag), r.priority, r.daysUntilEnd, getFlagAction(r.flag), r.coverageEndDate || "", r.reason || "", ]); const csv = [headers, ...rows] .map((row) => row.map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")) .join("\r\n"); downloadBlob(new Blob([csv], { type: "text/csv;charset=utf-8;" }), filename); }; return ( ); }