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;

export class ExpensePdf {
    static async generate(
        expenses: any[],
        res: Response,
        filters?: { startDate?: string; endDate?: string; search?: string }
    ) {
        const doc = new PDFDocument({
            size: "A4",
            margin: PAGE_MARGIN,
            bufferPages: true,
        });

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

        const pageWidth = doc.page.width - PAGE_MARGIN * 2;

        // ── Shared header (logo + shop details) ──
        await PdfHeader.draw(doc, pageWidth, PAGE_MARGIN, "EXPENSE REPORT");

        // ── Optional filter sub-line ──
        this.drawFilterLine(doc, pageWidth, filters);

        // ── Body ──
        this.drawTable(doc, expenses, pageWidth);
        this.drawTotals(doc, expenses, pageWidth);
        this.drawFooter(doc, pageWidth);

        doc.end();
    }

    // ----------------------------------------------------------------
    // Filter sub-line (date range / search keyword)
    // ----------------------------------------------------------------
    private static drawFilterLine(
        doc: PDFKit.PDFDocument,
        pageWidth: number,
        filters?: { startDate?: string; endDate?: string; search?: string }
    ) {
        const parts: string[] = [];
        if (filters?.startDate)
            parts.push(`From: ${new Date(filters.startDate).toLocaleDateString("en-GB").replace(/\//g, "-")}`);
        if (filters?.endDate)
            parts.push(`To: ${new Date(filters.endDate).toLocaleDateString("en-GB").replace(/\//g, "-")}`);
        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;
    }

    // ----------------------------------------------------------------
    // Table
    // ----------------------------------------------------------------
    private static drawTable(
        doc: PDFKit.PDFDocument,
        expenses: any[],
        pageWidth: number
    ) {
        const cols = {
            no: { x: PAGE_MARGIN, width: pageWidth * 0.06 },
            date: { x: PAGE_MARGIN + pageWidth * 0.06, width: pageWidth * 0.14 },
            category: { x: PAGE_MARGIN + pageWidth * 0.20, width: pageWidth * 0.26 },
            paymentMode: { x: PAGE_MARGIN + pageWidth * 0.46, width: pageWidth * 0.18 },
            remarks: { x: PAGE_MARGIN + pageWidth * 0.64, width: pageWidth * 0.20 },
            amount: { x: PAGE_MARGIN + pageWidth * 0.84, width: pageWidth * 0.16 },
        };

        const rowHeight = 24;
        const headerH = 26;

        // ── Table header (no background — just a bottom border) ──
        const drawTableHeader = () => {
            const y = doc.y;
            doc
                .font("Helvetica-Bold")
                .fontSize(8.5)
                .fillColor(COLORS.primary)
                .text("#", cols.no.x, y + 6, { width: cols.no.width, align: "center" })
                .text("DATE", cols.date.x, y + 6, { width: cols.date.width })
                .text("CATEGORY", cols.category.x, y + 6, { width: cols.category.width })
                .text("PAYMENT", cols.paymentMode.x, y + 6, { width: cols.paymentMode.width })
                .text("REMARKS", cols.remarks.x, y + 6, { width: cols.remarks.width })
                .text("AMOUNT", cols.amount.x, y + 6, { width: cols.amount.width - 6, align: "right" });

            doc.y = y + headerH;

            // Underline the header row
            doc
                .moveTo(PAGE_MARGIN, doc.y)
                .lineTo(PAGE_MARGIN + pageWidth, doc.y)
                .strokeColor(COLORS.primary)
                .lineWidth(1)
                .stroke();

            doc.y += 4;
        };

        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();

        expenses.forEach((exp, i) => {
            ensureSpace(rowHeight);
            const y = doc.y;

            // Alternate row tint (very subtle, no heavy coloured band)
            if (i % 2 === 1) {
                doc.rect(PAGE_MARGIN, y, pageWidth, rowHeight).fill(COLORS.rowAlt);
            }

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

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

            doc.font("Helvetica").fontSize(9).fillColor(COLORS.text);
            doc.text(dateStr, cols.date.x, y + 5, { width: cols.date.width });
            doc.text(exp.category ?? "-", cols.category.x, y + 5, {
                width: cols.category.width - 4,
                ellipsis: true,
                lineBreak: false,
            });
            doc.text(exp.paymentMode ?? "-", cols.paymentMode.x, y + 5, { width: cols.paymentMode.width });
            doc.text(exp.remarks ?? "-", cols.remarks.x, y + 5, {
                width: cols.remarks.width - 4,
                ellipsis: true,
                lineBreak: false,
            });
            doc
                .font("Helvetica-Bold")
                .fontSize(9)
                .fillColor(COLORS.primary)
                .text(this.formatCurrency(exp.amount), cols.amount.x, y + 5, {
                    width: cols.amount.width - 6,
                    align: "right",
                });

            doc.y = y + rowHeight;
        });

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

        doc.y += 14;
    }

    // ----------------------------------------------------------------
    // Grand total block (text only, no coloured box)
    // ----------------------------------------------------------------
    private static drawTotals(
        doc: PDFKit.PDFDocument,
        expenses: any[],
        pageWidth: number
    ) {
        const total = expenses.reduce((sum, e) => sum + Number(e.amount ?? 0), 0);
        const boxWidth = pageWidth * 0.38;
        const labelX = PAGE_MARGIN + pageWidth - boxWidth;

        const y = doc.y;

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

        doc.y = y + 6;

        doc
            .font("Helvetica-Bold")
            .fontSize(11)
            .fillColor(COLORS.primary)
            .text("TOTAL EXPENSES:", labelX, doc.y, { width: boxWidth * 0.58 })
            .text(this.formatCurrency(total), labelX, doc.y - 13.5, {
                width: boxWidth,
                align: "right",
            });

        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 expense report.",
                PAGE_MARGIN,
                y,
                { width: pageWidth, align: "center" }
            );
    }

    // ----------------------------------------------------------------
    // Helpers
    // ----------------------------------------------------------------
    private static formatCurrency(val: any): string {
        const num = Number(val);
        if (isNaN(num)) return "Rs. 0.00";
        return `Rs. ${num.toFixed(2)}`;
    }
}
