import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import { format } from "date-fns";

interface LegalCaseRow {
  title: string;
  caseNumber: string;
  association: string;
  unit: string;
  stage: string;
  caseType: string;
  amountDue: number;
  attorney: string;
  status: string;
  openedDate: string | null;
}

export function exportLegalMattersPdf(
  rows: LegalCaseRow[],
  title = "Legal Cases Report"
) {
  const doc = new jsPDF({ orientation: "landscape" });
  const now = format(new Date(), "MMM d, yyyy h:mm a");

  doc.setFontSize(18);
  doc.text(title, 14, 20);
  doc.setFontSize(9);
  doc.setTextColor(100);
  doc.text(`Generated: ${now}  •  ${rows.length} cases`, 14, 27);
  doc.setTextColor(0);

  const totalDue = rows.reduce((s, r) => s + r.amountDue, 0);
  doc.setFontSize(10);
  doc.text(`Total Amount Due: $${totalDue.toLocaleString(undefined, { minimumFractionDigits: 2 })}`, 14, 34);

  const fmt = (n: number) =>
    "$" + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  autoTable(doc, {
    startY: 40,
    head: [[
      "Title", "Case #", "Association", "Unit", "Stage",
      "Type", "Amount Due", "Attorney", "Status", "Opened"
    ]],
    body: rows.map((r) => [
      r.title,
      r.caseNumber || "—",
      r.association,
      r.unit || "—",
      r.stage,
      r.caseType,
      fmt(r.amountDue),
      r.attorney || "—",
      r.status,
      r.openedDate ? format(new Date(r.openedDate), "MM/dd/yyyy") : "—",
    ]),
    styles: { fontSize: 7, cellPadding: 2 },
    headStyles: { fillColor: [124, 58, 237], fontSize: 7 },
    alternateRowStyles: { fillColor: [245, 247, 250] },
    didDrawPage: (data: any) => {
      const pageCount = doc.getNumberOfPages();
      doc.setFontSize(7);
      doc.setTextColor(150);
      doc.text(
        `Page ${data.pageNumber} of ${pageCount}`,
        doc.internal.pageSize.width - 30,
        doc.internal.pageSize.height - 8
      );
    },
  });

  doc.save(`Legal_Cases_Report_${format(new Date(), "yyyy-MM-dd")}.pdf`);
}
