import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, Table, TableCell, TableRow, TextRun, WidthType } from "docx";
import PDFDocument from "pdfkit";
import { showCell, type Cell } from "../../core/files/table.js";
import { dmy } from "../../shared/dates.js";

export interface Section { title: string; pairs?: [string, string][]; header?: string[]; rows?: Cell[][] }
export interface Report { title: string; subtitle: string; sections: Section[] }
const face = (bold: boolean) => (bold ? "Helvetica-Bold" : "Helvetica");
const write = (doc: PDFKit.PDFDocument, t: string, bold: boolean, x: number, y: number, o: PDFKit.Mixins.TextOptions) => { doc.font(face(bold)).text(t, x, y, o); };
const height = (doc: PDFKit.PDFDocument, t: string, bold: boolean, width: number) => doc.font(face(bold)).heightOfString(t || " ", { width });
const text = (v: Cell) => (v === null ? "" : String(showCell(v)));
export function toPdf(r: Report): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const wide = r.sections.some((s) => (s.header?.length ?? 0) > 6), doc = new PDFDocument({ size: "A4", layout: wide ? "landscape" : "portrait", margin: 40, bufferPages: true, info: { Title: r.title } }), chunks: Buffer[] = [];
    doc.on("data", (b: Buffer) => chunks.push(b)).on("end", () => resolve(Buffer.concat(chunks))).on("error", reject);
    const W = doc.page.width - 80, bottom = () => doc.page.height - 60;
    doc.rect(40, 40, W, 54).fill("#0f5257").fillColor("#fff").fontSize(16);
    write(doc, r.title, true, 52, 47, { width: W - 24, height: 22, ellipsis: true });
    doc.fontSize(9);
    write(doc, dmy(r.subtitle), false, 52, 74, { width: W - 24 });
    let y = 110;
    const space = (h: number) => { if (y + h > bottom()) { doc.addPage(); y = 40; } };
    for (const s of r.sections) {
      space(40);
      doc.fillColor("#0f5257").fontSize(12); write(doc, s.title, true, 40, y, { width: W }); y += 20;
      for (const [k, raw] of s.pairs ?? []) { const v = dmy(raw); doc.fontSize(9); const h = Math.max(14, height(doc, v, false, W - 180) + 4); space(h); doc.fillColor("#555"); write(doc, k, false, 40, y, { width: 170 }); doc.fillColor("#111"); write(doc, v, false, 220, y, { width: W - 180 }); y += h; }
      if (s.header) {
        const n = s.header.length, weight = s.header.map((h, i) => Math.min(32, Math.max(6, h.length, ...(s.rows ?? []).slice(0, 80).map((x) => text(x[i] ?? null).length)))), sum = weight.reduce((a, b) => a + b, 0), w = weight.map((x) => (x / sum) * W);
        const line = (cells: string[], head: boolean) => { doc.fontSize(8); const h = Math.max(...cells.map((c, i) => height(doc, c, head, w[i]! - 8))) + 8; if (y + h > bottom()) { doc.addPage(); y = 40; if (!head) line(s.header!, true); doc.fontSize(8); } if (head) doc.rect(40, y, W, h).fill("#e8f0ef"); let x = 40; doc.fillColor("#111"); cells.forEach((c, i) => { write(doc, c, head, x + 4, y + 4, { width: w[i]! - 8 }); x += w[i]!; }); doc.moveTo(40, y + h).lineTo(40 + W, y + h).lineWidth(0.5).strokeColor("#ccc").stroke(); y += h; };
        line(s.header, true);
        for (const row of s.rows ?? []) line(Array.from({ length: n }, (_, i) => text(row[i] ?? null)), false);
        if (!s.rows?.length) line(["No records", ...Array<string>(n - 1).fill("")], false);
      }
      y += 14;
    }
    const pages = doc.bufferedPageRange();
    for (let i = 0; i < pages.count; i++) { doc.switchToPage(i); doc.page.margins.bottom = 0; doc.fillColor("#777").font("Helvetica").fontSize(8).text(`Page ${i + 1} of ${pages.count}`, 40, doc.page.height - 34, { width: W, align: "right" }); }
    doc.end();
  });
}
export function toDocx(r: Report): Promise<Buffer> {
  const cell = (t: string, bold = false) => new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: t, bold, size: 18 })] })], ...(bold ? { shading: { fill: "E8F0EF" } } : {}) });
  const body = r.sections.flatMap((s) => [new Paragraph({ text: s.title, heading: HeadingLevel.HEADING_2, spacing: { before: 240, after: 80 } }), ...(s.pairs ?? []).map(([k, v]) => new Paragraph({ children: [new TextRun({ text: `${k}: `, bold: true, size: 20 }), new TextRun({ text: dmy(v), size: 20 })] })), ...(s.header ? [new Table({ width: { size: 100, type: WidthType.PERCENTAGE }, rows: [new TableRow({ tableHeader: true, children: s.header.map((h) => cell(h, true)) }), ...(s.rows ?? []).map((x) => new TableRow({ children: s.header!.map((_, i) => cell(text(x[i] ?? null))) }))] })] : [])]);
  return Packer.toBuffer(new Document({ sections: [{ children: [new Paragraph({ text: r.title, heading: HeadingLevel.HEADING_1 }), new Paragraph({ alignment: AlignmentType.LEFT, children: [new TextRun({ text: dmy(r.subtitle), italics: true, size: 18 })] }), ...body] }] }));
}
