import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { formatDateTimeEST, formatDateLongEST } from "./timezoneUtils";

const MARGIN = 54; // 0.75"
const PAGE_W = 612;
const PAGE_H = 792;

function header(doc: jsPDF, title: string, subtitle: string) {
  doc.setFont("helvetica", "bold");
  doc.setFontSize(18);
  doc.setTextColor(15, 23, 42);
  doc.text(title, MARGIN, MARGIN);
  doc.setFont("helvetica", "normal");
  doc.setFontSize(10);
  doc.setTextColor(100);
  doc.text(subtitle, MARGIN, MARGIN + 16);
  doc.setDrawColor(200);
  doc.setLineWidth(0.5);
  doc.line(MARGIN, MARGIN + 24, PAGE_W - MARGIN, MARGIN + 24);
}

function footer(doc: jsPDF, generated: string) {
  const pages = doc.getNumberOfPages();
  for (let i = 1; i <= pages; i++) {
    doc.setPage(i);
    doc.setFont("helvetica", "normal");
    doc.setFontSize(8);
    doc.setTextColor(140);
    doc.text(`Generated ${generated}`, MARGIN, PAGE_H - 24);
    doc.text(`Page ${i} of ${pages}`, PAGE_W - MARGIN, PAGE_H - 24, { align: "right" });
  }
}

function sectionTitle(doc: jsPDF, text: string, y: number): number {
  if (y > PAGE_H - 100) { doc.addPage(); y = MARGIN; }
  doc.setFont("helvetica", "bold");
  doc.setFontSize(12);
  doc.setTextColor(30, 41, 59);
  doc.text(text.toUpperCase(), MARGIN, y);
  doc.setDrawColor(59, 130, 246);
  doc.setLineWidth(1);
  doc.line(MARGIN, y + 4, MARGIN + 60, y + 4);
  return y + 18;
}

function fmtAddress(a: any): string {
  const parts = [a.address, [a.city, a.state].filter(Boolean).join(", "), a.zip].filter(Boolean);
  return parts.join("  ");
}

function kvRows(rows: Array<[string, any]>): string[][] {
  return rows
    .filter(([, v]) => v !== null && v !== undefined && String(v).trim() !== "")
    .map(([k, v]) => [k, String(v)]);
}

function drawKvTable(doc: jsPDF, rows: string[][], startY: number): number {
  if (!rows.length) {
    doc.setFont("helvetica", "italic");
    doc.setFontSize(10);
    doc.setTextColor(140);
    doc.text("None on file.", MARGIN, startY);
    return startY + 16;
  }
  autoTable(doc, {
    startY,
    body: rows,
    theme: "plain",
    styles: { font: "helvetica", fontSize: 10, cellPadding: 4, textColor: 30 },
    columnStyles: {
      0: { cellWidth: 150, fontStyle: "bold", textColor: 80 },
      1: { cellWidth: "auto" },
    },
    margin: { left: MARGIN, right: MARGIN },
  });
  return (doc as any).lastAutoTable.finalY + 12;
}

export function exportAssociationBinderPdf(opts: {
  association: any;
  boardMembers: any[];
  bankAccounts: any[];
  customFields: any[];
  units: any[];
  owners: any[];
  faqs?: any[];
}) {
  const { association: a, boardMembers, bankAccounts, customFields, units, owners, faqs } = opts;
  const doc = new jsPDF({ unit: "pt", format: "letter" });
  const generated = formatDateTimeEST(new Date());

  header(doc, a.name || "Association", `Association Binder · ${formatDateLongEST(new Date())}`);
  let y = MARGIN + 44;

  y = sectionTitle(doc, "General Information", y);
  y = drawKvTable(doc, kvRows([
    ["Name", a.name],
    ["Physical Address", fmtAddress(a)],
    ["Mailing Address", a.mailing_address],
    ["Care Of", a.care_of_address],
    ["Phone", a.phone],
    ["Email", a.email],
    ["Contact Email", a.contact_email],
    ["Website", a.website],
    ["Management Fee", a.management_fee != null ? `$${Number(a.management_fee).toFixed(2)}` : ""],
    ["Fiscal Year Start (Month)", a.fiscal_year_start],
    ["Total Units", units?.length ?? ""],
    ["Active Owners", owners?.length ?? ""],
    ["Status", a.status || "active"],
  ]), y);

  y = sectionTitle(doc, "Legal Counsel", y);
  y = drawKvTable(doc, kvRows([
    ["Attorney", a.attorney_name],
    ["Firm", a.attorney_firm],
    ["Email", a.attorney_email],
    ["Phone", a.attorney_phone],
  ]), y);

  y = sectionTitle(doc, "Accounting / CPA", y);
  y = drawKvTable(doc, kvRows([
    ["CPA", a.cpa_name],
    ["Firm", a.cpa_firm],
    ["Email", a.cpa_email],
    ["Phone", a.cpa_phone],
  ]), y);

  y = sectionTitle(doc, "Insurance", y);
  y = drawKvTable(doc, kvRows([
    ["Provider", a.insurance_provider],
    ["Expiration", a.insurance_expiration],
  ]), y);

  // Board members
  y = sectionTitle(doc, "Board of Directors", y);
  if (boardMembers?.length) {
    autoTable(doc, {
      startY: y,
      head: [["Name", "Position", "Email", "Phone", "Term Ends"]],
      body: boardMembers.map((b) => [
        b.member_name || "", b.position || "", b.email || "", b.phone || "",
        b.term_end_date ? formatDateLongEST(b.term_end_date) : "",
      ]),
      theme: "striped",
      styles: { font: "helvetica", fontSize: 9, cellPadding: 4 },
      headStyles: { fillColor: [30, 41, 59], textColor: 255 },
      margin: { left: MARGIN, right: MARGIN },
    });
    y = (doc as any).lastAutoTable.finalY + 12;
  } else {
    y = drawKvTable(doc, [], y);
  }

  // Bank accounts
  y = sectionTitle(doc, "Bank Accounts", y);
  if (bankAccounts?.length) {
    autoTable(doc, {
      startY: y,
      head: [["Account Name", "Bank", "Type", "Last 4"]],
      body: bankAccounts.map((b) => [
        b.account_name || "", b.bank_name || "", b.account_type || "",
        b.account_number ? `****${String(b.account_number).slice(-4)}` : "",
      ]),
      theme: "striped",
      styles: { font: "helvetica", fontSize: 9, cellPadding: 4 },
      headStyles: { fillColor: [30, 41, 59], textColor: 255 },
      margin: { left: MARGIN, right: MARGIN },
    });
    y = (doc as any).lastAutoTable.finalY + 12;
  } else {
    y = drawKvTable(doc, [], y);
  }

  // Custom fields
  if (customFields?.length) {
    y = sectionTitle(doc, "Additional Information", y);
    y = drawKvTable(doc, customFields.map((c) => [c.field_label || "", c.field_value || ""]), y);
  }

  // Optional FAQs
  if (faqs?.length) {
    doc.addPage();
    y = MARGIN;
    y = sectionTitle(doc, "Frequently Asked Questions", y);
    y = drawFaqs(doc, faqs, y);
  }

  footer(doc, generated);
  doc.save(`${(a.name || "association").replace(/[^a-z0-9]+/gi, "_")}_Binder.pdf`);
}

function drawFaqs(doc: jsPDF, faqs: any[], startY: number): number {
  let y = startY;
  faqs.forEach((f, i) => {
    const q = `${i + 1}. ${f.question || ""}`;
    const a = f.answer || "";
    doc.setFont("helvetica", "bold");
    doc.setFontSize(11);
    doc.setTextColor(15, 23, 42);
    const qLines = doc.splitTextToSize(q, PAGE_W - MARGIN * 2);
    if (y + qLines.length * 14 > PAGE_H - 60) { doc.addPage(); y = MARGIN; }
    doc.text(qLines, MARGIN, y);
    y += qLines.length * 14 + 2;

    doc.setFont("helvetica", "normal");
    doc.setFontSize(10);
    doc.setTextColor(60);
    const aLines = doc.splitTextToSize(a, PAGE_W - MARGIN * 2);
    if (y + aLines.length * 13 > PAGE_H - 60) { doc.addPage(); y = MARGIN; }
    doc.text(aLines, MARGIN, y);
    y += aLines.length * 13 + 14;
  });
  return y;
}

export function exportAssociationFaqsPdf(opts: { association: any; faqs: any[] }) {
  const { association: a, faqs } = opts;
  const doc = new jsPDF({ unit: "pt", format: "letter" });
  const generated = formatDateTimeEST(new Date());

  header(doc, a.name || "Association", `Frequently Asked Questions · ${formatDateLongEST(new Date())}`);
  let y = MARGIN + 44;

  if (!faqs?.length) {
    doc.setFont("helvetica", "italic");
    doc.setFontSize(11);
    doc.setTextColor(120);
    doc.text("No FAQs on file.", MARGIN, y);
  } else {
    y = drawFaqs(doc, faqs, y);
  }

  footer(doc, generated);
  doc.save(`${(a.name || "association").replace(/[^a-z0-9]+/gi, "_")}_FAQs.pdf`);
}
