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

export const generateMonthEndReportPDF = (clientName, startDate, endDate, reportData) => {
  // Use Letter size with Point units (612x792)
  const doc = new jsPDF({ format: "letter", unit: "pt" });
  const pageWidth = doc.internal.pageSize.width;
  const pageHeight = doc.internal.pageSize.height;

  // Helper for layout
  const centerX = pageWidth / 2;
  let finalY = 0;

  // --- Cover Page ---
  // Background
  doc.setFillColor(248, 250, 252); // slate-50
  doc.rect(0, 0, pageWidth, pageHeight, "F");

  // Top Header Area (mocking the background image space)
  doc.setFillColor(203, 213, 225); // slate-300 placeholder for image
  doc.rect(0, 0, pageWidth, pageHeight * 0.35, "F");

  const contentStartY = pageHeight * 0.35 + 60;

  // Title Section
  doc.setFontSize(36);
  doc.setFont("times", "bold");
  doc.setTextColor(15, 23, 42); // slate-900
  doc.text("MANAGEMENT", centerX, contentStartY + 55, { align: "center" });
  doc.text("REPORT", centerX, contentStartY + 95, { align: "center" });

  // Client Name Section
  const clientSectionY = contentStartY + 180;
  doc.setFontSize(10);
  doc.setFont("times", "normal");
  doc.setTextColor(100, 116, 139); // slate-500
  doc.text("PREPARED FOR", centerX, clientSectionY, { align: "center", charSpace: 2 });

  doc.setDrawColor(203, 213, 225); // slate-300
  doc.line(centerX - 60, clientSectionY + 8, centerX + 60, clientSectionY + 8);

  doc.setFontSize(24);
  doc.setFont("times", "bold");
  doc.setTextColor(30, 41, 59); // slate-800
  doc.text(clientName || "Association Name", centerX, clientSectionY + 40, { align: "center" });

  // Date Section
  const dateSectionY = clientSectionY + 100;
  doc.setFillColor(255, 255, 255);
  doc.setDrawColor(226, 232, 240); // slate-200
  doc.rect(centerX - 100, dateSectionY - 20, 200, 36, "FD"); // Box

  doc.setFontSize(12);
  doc.setFont("times", "normal");
  doc.setTextColor(15, 23, 42); // slate-900
  doc.text(`${format(new Date(endDate), "MMMM yyyy")}`, centerX, dateSectionY + 4, { align: "center", charSpace: 1 });

  // Prepared By Section
  const preparedByY = pageHeight - 80;
  doc.setDrawColor(226, 232, 240); // slate-200
  doc.line(40, preparedByY - 20, pageWidth - 40, preparedByY - 20);

  doc.setFontSize(9);
  doc.setFont("times", "normal");
  doc.setTextColor(148, 163, 184); // slate-400
  doc.text("PREPARED BY", centerX, preparedByY, { align: "center", charSpace: 1 });

  doc.setFontSize(12);
  doc.setFont("times", "bold");
  doc.setTextColor(30, 41, 59); // slate-800
  doc.text("Avria Community Management, LLC", centerX, preparedByY + 16, { align: "center" });

  // Bottom Decorative Bar
  doc.setFillColor(15, 23, 42); // slate-900
  doc.rect(0, pageHeight - 12, pageWidth, 12, "F");

  // --- New Page for Content ---
  doc.addPage();
  finalY = 50;

  // --- Helper to add section headers ---
  const addSectionHeader = (title) => {
    // Check if we need a page break (Letter height ~792pt, minus margin)
    if (finalY > 700) {
      doc.addPage();
      finalY = 50;
    }
    doc.setFontSize(14);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 41, 59);
    doc.text(title, 40, finalY);
    finalY += 20;
  };

  // --- ARC Applications ---
  if (reportData.arcApplications?.length > 0) {
    addSectionHeader("ARC Applications");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Address", "Description", "Status"]],
      body: reportData.arcApplications.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.address || "-",
        item.description || item.title || "-",
        item.status,
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Bids & Quotes ---
  if (reportData.bidsQuotes?.length > 0) {
    addSectionHeader("Bids & Quotes");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Title", "Description"]],
      body: reportData.bidsQuotes.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.title,
        item.description || "-",
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Call Logs ---
  if (reportData.callLogs?.length > 0) {
    addSectionHeader("Call Logs");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Caller", "Duration", "Notes"]],
      body: reportData.callLogs.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.caller_name || "Unknown",
        item.duration ? `${item.duration}m` : "-",
        item.notes || "-",
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Collections ---
  if (reportData.collections?.length > 0) {
    addSectionHeader("Collections Activity");
    autoTable(doc, {
      startY: finalY,
      head: [["Address", "Status", "Stage", "Amount Due", "Last Update"]],
      body: reportData.collections.map((item) => [
        item.address,
        item.status,
        item.stage ? item.stage.replace(/_/g, " ") : "-",
        `$${item.amount_due || "0.00"}`,
        format(new Date(item.updated_at || item.created_at), "MMM d, yyyy"),
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Estoppels ---
  if (reportData.estoppels?.length > 0) {
    addSectionHeader("Estoppels");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Address", "Status", "Notes"]],
      body: reportData.estoppels.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.address,
        item.status,
        item.notes || "-",
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Homeowner Requests ---
  if (reportData.homeownerRequests?.length > 0) {
    addSectionHeader("Homeowner Requests");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Title", "Address", "Status"]],
      body: reportData.homeownerRequests.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.title,
        item.address_selected || "-",
        item.status,
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Legal Matters ---
  if (reportData.legalMatters?.length > 0) {
    addSectionHeader("Legal Matters");
    autoTable(doc, {
      startY: finalY,
      head: [["Title", "Case No", "Status", "Updated"]],
      body: reportData.legalMatters.map((item) => [
        item.title,
        item.case_no || "-",
        item.current_stage || "-",
        format(new Date(item.updated_at || item.created_at), "MMM d, yyyy"),
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Owner Updates ---
  if (reportData.ownerUpdates?.length > 0) {
    addSectionHeader("Owner Updates");
    autoTable(doc, {
      startY: finalY,
      head: [["Date Posted", "Content Preview"]],
      body: reportData.ownerUpdates.map((item) => [
        format(new Date(item.posted_at || item.created_at), "MMM d, yyyy"),
        item.content ? item.content.substring(0, 60) + (item.content.length > 60 ? "..." : "") : "-",
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Status Updates ---
  if (reportData.statusUpdates?.length > 0) {
    addSectionHeader("Status Updates");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Title", "Content Preview"]],
      body: reportData.statusUpdates.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.title,
        item.content ? item.content.substring(0, 60) + (item.content.length > 60 ? "..." : "") : "-",
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // --- Violations ---
  if (reportData.violations?.length > 0) {
    addSectionHeader("Violations");
    autoTable(doc, {
      startY: finalY,
      head: [["Date", "Address", "Type", "Status"]],
      body: reportData.violations.map((item) => [
        format(new Date(item.created_at), "MMM d, yyyy"),
        item.address || "-",
        item.violation_type || "-",
        item.status,
      ]),
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      margin: { left: 40, right: 40 },
    });
    finalY = doc.lastAutoTable.finalY + 30;
  }

  // Save the PDF
  const filename = `${clientName.replace(/\s+/g, "_")}_MonthEndReport_${format(new Date(startDate), "yyyyMMdd")}_${format(new Date(endDate), "yyyyMMdd")}.pdf`;
  doc.save(filename);
};
