import { useAuth } from "@clerk/react";
import { exportFromBackend, exportLinesFromBackend } from "../lib/api";
import { getFlagLabel, getFlagAction, getDeviceDisplay } from "../lib/coverage";

// One export row per device coverage line (P6 granularity, locked 2026-07-07).
function patientsToLineRows(patients) {
  const rows = [];
  for (const p of patients) {
    for (const line of p.lines || []) {
      if (!line.gradeable) continue; // non-CGM lines carry no readiness actions
      const by = {};
      (line.doc_items || []).forEach((i) => {
        by[i.doc_type] = i.value || (i.required_state === "NOT_REQUIRED" ? "Not required" : "Not on file");
      });
      rows.push({
        patient_id: p.patient_id,
        device_display: line.device_display,
        payer: line.payer || "",
        plan_type: line.plan_type,
        rollup_status: p.rollup_status,
        line_status: line.line_status,
        timing: line.timing_flag || "",
        order_numbers: (line.order_numbers || []).join(", "),
        hcpcs_codes: (line.hcpcs_codes || []).join(", "),
        total_quantity: line.total_quantity || 0,
        shipment_date: line.shipment_date || "",
        swo: by.swo || "",
        visit: by.visit || "",
        pecos: by.pecos || "",
        pa: by.pa || "",
        diagnosis: by.diagnosis || "",
      });
    }
  }
  return rows;
}

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, patients = null, 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) && !(patients && patients.length)) return;

    // Nested view: one row per device coverage line, exported through the
    // backend so the WORM audit trail records it.
    if (patients && patients.length) {
      const token = await getToken().catch(() => null);
      try {
        const blob = await exportLinesFromBackend(patientsToLineRows(patients), batchId, token);
        if (blob) {
          downloadBlob(blob, filename);
          return;
        }
      } catch {
        // fall through to the legacy paths below
      }
    }

    if (batchId && records && records.length) {
      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",
      "Visit Confidence",
    ];
    const rows = records.map((r) => [
      r.patient_id,
      r.device_display || getDeviceDisplay(r.device_type),
      r.payer,
      r.status_label || getFlagLabel(r.flag),
      r.priority_score ?? r.priority,
      r.days_until_coverage_end ?? r.daysUntilEnd,
      r.action || getFlagAction(r.flag),
      r.coverage_end_date || r.coverageEndDate || "",
      r.reason || "",
      r.visit_date_confidence || "estimated",
    ]);
    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 (
    <button
      onClick={exportCSV}
      className="bg-[var(--brand)] text-warm-white px-4 py-[7px] rounded-md text-[13px] font-medium cursor-pointer transition-colors hover:bg-[var(--brand-hover)] font-body"
      disabled={!records || records.length === 0}
    >
      ↓ Export Work Queue
    </button>
  );
}