import PDFDocument from "pdfkit";
import type { Response } from "express";
import { PdfHeader } from "./components/PdfHeader.js";

// ── Design tokens ──────────────────────────────────────────────────
const COLORS = {
    primary: "#0F5132",
    accent: "#198754",
    text: "#212529",
    muted: "#6C757D",
    border: "#DEE2E6",
    rowAlt: "#F8F9FA",
    white: "#FFFFFF",
};

const PAGE_MARGIN = 40;

// ── Helpers ────────────────────────────────────────────────────────
function fmt(value: number | string | undefined | null): string {
    const n = Number(value ?? 0);
    return isNaN(n) ? "-" : n.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function fmtNum(value: number | string | undefined | null): string {
    const n = Number(value ?? 0);
    return isNaN(n) ? "-" : n.toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export class PurchaseReportPdf {
    /**
     * Generates and streams a Purchase Report PDF to the Express response.
     *
     * @param purchases  Raw purchase records (from ReportService.getExportData)
     * @param res        Express Response to pipe into
     * @param filters    Optional filter meta for the sub-header line
     */
    static async generate(
        purchases: any[],
        res: Response,
        filters?: {
            search?: string;
            dateFrom?: string;
            dateTo?: string;
            supplier?: string;
            vegetable?: string;
            outstandingBalance?: number;
        }
    ) {
        const doc = new PDFDocument({
            size: "A4",
            layout: "landscape",
            margin: PAGE_MARGIN,
            bufferPages: true,
        });

        res.setHeader("Content-Type", "application/pdf");
        res.setHeader(
            "Content-Disposition",
            `attachment; filename="purchase-report-${Date.now()}.pdf"`
        );
        res.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        doc.pipe(res);

        // Landscape A4: usable width = 841.89 − 2 × 40
        const pageWidth = doc.page.width - PAGE_MARGIN * 2;

        await PdfHeader.draw(doc, pageWidth, PAGE_MARGIN, "PURCHASE REPORT");

        this.drawFilterLine(doc, pageWidth, filters);
        this.drawTable(doc, purchases, pageWidth);
        this.drawTotals(doc, purchases, pageWidth, filters?.outstandingBalance);
        this.drawFooter(doc, pageWidth);

        doc.end();
    }

    // ── Filter sub-line ────────────────────────────────────────────
    private static drawFilterLine(
        doc: PDFKit.PDFDocument,
        pageWidth: number,
        filters?: {
            search?: string;
            dateFrom?: string;
            dateTo?: string;
            supplier?: string;
            vegetable?: string;
        }
    ) {
        const parts: string[] = [];
        if (filters?.dateFrom)
            parts.push(`From: ${new Date(filters.dateFrom).toLocaleDateString("en-GB").replace(/\//g, "-")}`);
        if (filters?.dateTo)
            parts.push(`To: ${new Date(filters.dateTo).toLocaleDateString("en-GB").replace(/\//g, "-")}`);
        if (filters?.supplier) parts.push(`Supplier: ${filters.supplier}`);
        if (filters?.vegetable) parts.push(`Vegetable: ${filters.vegetable}`);
        if (filters?.search) parts.push(`Search: "${filters.search}"`);

        if (parts.length) {
            doc
                .font("Helvetica")
                .fontSize(8.5)
                .fillColor(COLORS.muted)
                .text(parts.join("   |   "), PAGE_MARGIN, doc.y, {
                    width: pageWidth,
                    align: "right",
                });
            doc.y += 4;
        }

        doc.y += 10;
    }

    // ── Main table ─────────────────────────────────────────────────
    private static drawTable(
        doc: PDFKit.PDFDocument,
        purchases: any[],
        pageWidth: number
    ) {
        // Column layout — landscape A4 pageWidth ≈ 761 pts
        // Percentages sum to 100 %
        const pw = pageWidth;
        const cols = {
            no:           { x: PAGE_MARGIN + pw * 0.000, width: pw * 0.030 },
            date:         { x: PAGE_MARGIN + pw * 0.030, width: pw * 0.085 },
            lotNo:        { x: PAGE_MARGIN + pw * 0.115, width: pw * 0.070 },
            supplier:     { x: PAGE_MARGIN + pw * 0.185, width: pw * 0.130 },
            vegetable:    { x: PAGE_MARGIN + pw * 0.315, width: pw * 0.095 },
            qty:          { x: PAGE_MARGIN + pw * 0.410, width: pw * 0.070 },
            bags:         { x: PAGE_MARGIN + pw * 0.480, width: pw * 0.050 },
            remQty:       { x: PAGE_MARGIN + pw * 0.530, width: pw * 0.075 },
            rate:         { x: PAGE_MARGIN + pw * 0.605, width: pw * 0.070 },
            grandTotal:   { x: PAGE_MARGIN + pw * 0.675, width: pw * 0.085 },
            costKg:       { x: PAGE_MARGIN + pw * 0.760, width: pw * 0.070 },
            advance:      { x: PAGE_MARGIN + pw * 0.830, width: pw * 0.075 },
            balance:      { x: PAGE_MARGIN + pw * 0.905, width: pw * 0.095 },
        };

        const rowHeight = 22;
        const headerH = 24;

        const drawTableHeader = () => {
            const y = doc.y;
            doc
                .font("Helvetica-Bold")
                .fontSize(7.5)
                .fillColor(COLORS.primary)
                .text("#",           cols.no.x,         y + 5, { width: cols.no.width,         align: "center" })
                .text("DATE",        cols.date.x,        y + 5, { width: cols.date.width })
                .text("LOT NO",      cols.lotNo.x,       y + 5, { width: cols.lotNo.width })
                .text("SUPPLIER",    cols.supplier.x,    y + 5, { width: cols.supplier.width })
                .text("VEGETABLE",   cols.vegetable.x,   y + 5, { width: cols.vegetable.width })
                .text("QTY (KG)",    cols.qty.x,         y + 5, { width: cols.qty.width,         align: "right" })
                .text("BAGS",        cols.bags.x,        y + 5, { width: cols.bags.width,        align: "right" })
                .text("REM. (KG)",   cols.remQty.x,      y + 5, { width: cols.remQty.width,      align: "right" })
                .text("RATE",        cols.rate.x,        y + 5, { width: cols.rate.width,        align: "right" })
                .text("GRAND TOTAL", cols.grandTotal.x,  y + 5, { width: cols.grandTotal.width,  align: "right" })
                .text("COST/KG",     cols.costKg.x,      y + 5, { width: cols.costKg.width,      align: "right" })
                .text("ADVANCE",     cols.advance.x,     y + 5, { width: cols.advance.width,     align: "right" })
                .text("BALANCE",     cols.balance.x,     y + 5, { width: cols.balance.width - 4, align: "right" });

            doc.y = y + headerH;

            doc
                .moveTo(PAGE_MARGIN, doc.y)
                .lineTo(PAGE_MARGIN + pw, doc.y)
                .strokeColor(COLORS.primary)
                .lineWidth(1)
                .stroke();

            doc.y += 3;
        };

        const ensureSpace = (needed: number) => {
            const bottomLimit = doc.page.height - PAGE_MARGIN - 60;
            if (doc.y + needed > bottomLimit) {
                doc.addPage();
                doc.y = PAGE_MARGIN;
                drawTableHeader();
            }
        };

        drawTableHeader();

        purchases.forEach((p, i) => {
            ensureSpace(rowHeight);
            const y = doc.y;

            if (i % 2 === 1) {
                doc.rect(PAGE_MARGIN, y, pw, rowHeight).fill(COLORS.rowAlt);
            }

            const dateStr = p.purchaseDate
                ? new Date(p.purchaseDate).toLocaleDateString("en-GB").replace(/\//g, "-")
                : "-";

            // Row number
            doc
                .font("Helvetica-Bold")
                .fontSize(7.5)
                .fillColor(COLORS.accent)
                .text(`${i + 1}`, cols.no.x, y + 4, { width: cols.no.width, align: "center" });

            // Text columns
            doc.font("Helvetica").fontSize(8).fillColor(COLORS.text);
            doc.text(dateStr,                          cols.date.x,      y + 4, { width: cols.date.width - 4,     lineBreak: false });
            doc.text(p.lotNo ?? "-",                   cols.lotNo.x,     y + 4, { width: cols.lotNo.width - 4,    ellipsis: true, lineBreak: false });
            doc.text(p.supplier?.name ?? p.cashSupplierName ?? p.supplierName ?? "-", cols.supplier.x, y + 4, { width: cols.supplier.width - 4, ellipsis: true, lineBreak: false });
            doc.text(p.vegetable?.name ?? "-",         cols.vegetable.x, y + 4, { width: cols.vegetable.width - 4,ellipsis: true, lineBreak: false });

            // Numeric columns (right-aligned, green bold)
            doc.font("Helvetica").fontSize(8).fillColor(COLORS.text);
            doc.text(fmtNum(p.quantity),               cols.qty.x,        y + 4, { width: cols.qty.width - 2,        align: "right", lineBreak: false });
            doc.text(fmtNum(p.bags),                   cols.bags.x,       y + 4, { width: cols.bags.width - 2,       align: "right", lineBreak: false });
            doc.text(fmtNum(p.remainingQuantity),      cols.remQty.x,     y + 4, { width: cols.remQty.width - 2,     align: "right", lineBreak: false });
            doc.text(fmtNum(p.ratePerUnit),            cols.rate.x,       y + 4, { width: cols.rate.width - 2,       align: "right", lineBreak: false });

            doc.font("Helvetica-Bold").fontSize(8).fillColor(COLORS.primary);
            doc.text(fmt(p.grandTotal),                cols.grandTotal.x, y + 4, { width: cols.grandTotal.width - 2, align: "right", lineBreak: false });

            doc.font("Helvetica").fontSize(8).fillColor(COLORS.text);
            doc.text(fmt(p.costPerUnit),               cols.costKg.x,     y + 4, { width: cols.costKg.width - 2,     align: "right", lineBreak: false });
            doc.text(fmt(p.advanceAmount),             cols.advance.x,    y + 4, { width: cols.advance.width - 2,    align: "right", lineBreak: false });
            doc.text(fmt(p.balanceAmount),             cols.balance.x,    y + 4, { width: cols.balance.width - 6,    align: "right", lineBreak: false });

            doc.y = y + rowHeight;
        });

        // Bottom divider
        doc
            .moveTo(PAGE_MARGIN, doc.y)
            .lineTo(PAGE_MARGIN + pw, doc.y)
            .strokeColor(COLORS.border)
            .lineWidth(0.5)
            .stroke();

        doc.y += 12;
    }

    // ── Summary totals ─────────────────────────────────────────────
    private static drawTotals(
        doc: PDFKit.PDFDocument,
        purchases: any[],
        pageWidth: number,
        outstandingBalance?: number
    ) {
        const grandTotal     = purchases.reduce((s, p) => s + Number(p.grandTotal    ?? 0), 0);
        const advanceTotal   = purchases.reduce((s, p) => s + Number(p.advanceAmount ?? 0), 0);
        const balanceTotal   = purchases.reduce((s, p) => s + Number(p.balanceAmount ?? 0), 0);

        const boxWidth = pageWidth * 0.42;
        const labelX   = PAGE_MARGIN + pageWidth - boxWidth;
        const valX     = labelX + boxWidth * 0.58;
        const valWidth = boxWidth * 0.42;

        const y0 = doc.y;

        doc
            .moveTo(labelX, y0)
            .lineTo(PAGE_MARGIN + pageWidth, y0)
            .strokeColor(COLORS.primary)
            .lineWidth(0.75)
            .stroke();

        const drawRow = (label: string, value: string) => {
            doc.font("Helvetica").fontSize(9).fillColor(COLORS.text)
               .text(label, labelX, doc.y, { width: boxWidth * 0.58 });
            doc.font("Helvetica-Bold").fontSize(9).fillColor(COLORS.primary)
               .text(value, valX, doc.y - 12.5, { width: valWidth, align: "right" });
            doc.y += 4;
        };

        doc.y = y0 + 6;
        drawRow("Total Grand Total:",   fmt(grandTotal));
        drawRow("Total Advance:",       fmt(advanceTotal));
        drawRow("Purchase Balance:",    fmt(balanceTotal));

        if (outstandingBalance !== undefined) {
            doc.font("Helvetica-Bold").fontSize(10).fillColor(COLORS.primary);
            doc.text("Supplier Outstanding:", labelX, doc.y, { width: boxWidth * 0.58 });
            doc.font("Helvetica-Bold").fontSize(10).fillColor(COLORS.primary)
               .text(fmt(outstandingBalance), valX, doc.y - 14, { width: valWidth, align: "right" });
            doc.y += 4;
        }

        doc.y += 18;
    }

    // ── Footer ─────────────────────────────────────────────────────
    private static drawFooter(doc: PDFKit.PDFDocument, pageWidth: number) {
        const y = doc.page.height - PAGE_MARGIN - 20;
        doc
            .font("Helvetica-Oblique")
            .fontSize(8.5)
            .fillColor(COLORS.muted)
            .text(
                "This is a computer-generated purchase report.",
                PAGE_MARGIN,
                y,
                { width: pageWidth, align: "center" }
            );
    }
}
