import {
  AlignmentType,
  BorderStyle,
  ImageRun,
  Paragraph,
  ShadingType,
  Table,
  TableCell,
  TableRow,
  TextRun,
  WidthType,
} from "docx";
import PDFDocument from "pdfkit";
import { detectImageType, REPORT_THEME } from "./reportTheme.js";

export function buildDocxBrandingHeader(logo: Buffer | null, title: string, subtitle: string): Table {
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [
      new TableRow({
        children: [
          new TableCell({
            width: { size: 22, type: WidthType.PERCENTAGE },
            borders: {
              top: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              bottom: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              left: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              right: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
            },
            children: [
              new Paragraph({
                children: logo
                  ? [new ImageRun({ data: logo, type: detectImageType(logo), transformation: { width: 120, height: 50 } })]
                  : [new TextRun("")],
              }),
            ],
          }),
          new TableCell({
            width: { size: 78, type: WidthType.PERCENTAGE },
            borders: {
              top: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              bottom: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              left: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
              right: { style: BorderStyle.NONE, size: 0, color: "ffffff" },
            },
            children: [
              new Paragraph({
                alignment: AlignmentType.RIGHT,
                children: [new TextRun({ text: title, bold: true, size: 32, color: REPORT_THEME.primary })],
              }),
              new Paragraph({
                alignment: AlignmentType.RIGHT,
                children: [new TextRun({ text: subtitle, size: 20 })],
              }),
            ],
          }),
        ],
      }),
    ],
  });
}

export function buildDocxSectionHeading(title: string): Paragraph {
  return new Paragraph({ text: title, heading: "Heading2" });
}

export function buildDocxKeyValueTable(
  rows: Array<[string, string]>,
  keyWidthPct = 38,
): Table {
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: rows.map(
      ([k, v]) =>
        new TableRow({
          children: [
            new TableCell({
              shading: { fill: REPORT_THEME.lightBg, type: ShadingType.CLEAR, color: "auto" },
              width: { size: keyWidthPct, type: WidthType.PERCENTAGE },
              children: [new Paragraph({ children: [new TextRun({ text: k, bold: true })] })],
            }),
            new TableCell({
              width: { size: 100 - keyWidthPct, type: WidthType.PERCENTAGE },
              children: [new Paragraph(v)],
            }),
          ],
        }),
    ),
  });
}

export function buildDocxGridTable(headers: string[], rows: string[][]): Table {
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [
      new TableRow({
        children: headers.map(
          (h) =>
            new TableCell({
              shading: { fill: REPORT_THEME.primary, type: ShadingType.CLEAR, color: "auto" },
              children: [new Paragraph({ children: [new TextRun({ text: h, bold: true, color: REPORT_THEME.white })] })],
            }),
        ),
      }),
      ...rows.map(
        (r) =>
          new TableRow({
            children: r.map((c) => new TableCell({ children: [new Paragraph(c)] })),
          }),
      ),
    ],
  });
}

export class PdfReportLayout {
  doc: PDFKit.PDFDocument;
  pageWidth: number;
  pageBottomY: number;
  cursorY: number;
  private readonly logo: Buffer | null;

  constructor(doc: PDFKit.PDFDocument, logo: Buffer | null) {
    this.doc = doc;
    this.logo = logo;
    this.pageWidth = this.doc.page.width - this.doc.page.margins.left - this.doc.page.margins.right;
    this.pageBottomY = this.doc.page.height - this.doc.page.margins.bottom;
    this.cursorY = this.doc.page.margins.top;
  }

  drawHeader(title: string, subtitle: string) {
    const h = 90;
    this.doc.save();
    this.doc.rect(this.doc.page.margins.left, this.cursorY, this.pageWidth, h).fill(`#${REPORT_THEME.lightBg}`);
    this.doc.restore();

    if (this.logo) {
      try {
        this.doc.image(this.logo, this.doc.page.margins.left + 12, this.cursorY + 18, { fit: [110, 45], valign: "center" });
      } catch {
        // ignore logo rendering issues
      }
    }
    this.doc
      .fillColor(`#${REPORT_THEME.primary}`)
      .fontSize(20)
      .text(title, this.doc.page.margins.left + 140, this.cursorY + 20, { width: this.pageWidth - 150, align: "right" });
    this.doc
      .fillColor("#334155")
      .fontSize(10)
      .text(subtitle, this.doc.page.margins.left + 140, this.cursorY + 50, { width: this.pageWidth - 150, align: "right" });
    this.cursorY += h + 18;
  }

  ensureSpace(needed: number, title?: string, subtitle?: string) {
    if (this.cursorY + needed <= this.pageBottomY) return;
    this.doc.addPage();
    this.pageWidth = this.doc.page.width - this.doc.page.margins.left - this.doc.page.margins.right;
    this.pageBottomY = this.doc.page.height - this.doc.page.margins.bottom;
    this.cursorY = this.doc.page.margins.top;
    if (title && subtitle) this.drawHeader(title, subtitle);
  }

  sectionTitle(title: string, headerTitle: string, headerSubtitle: string) {
    this.ensureSpace(28, headerTitle, headerSubtitle);
    this.doc.fillColor(`#${REPORT_THEME.primary}`).fontSize(13).text(title, this.doc.page.margins.left, this.cursorY);
    this.cursorY += 18;
    this.doc
      .strokeColor("#cbd5e1")
      .lineWidth(1)
      .moveTo(this.doc.page.margins.left, this.cursorY)
      .lineTo(this.doc.page.margins.left + this.pageWidth, this.cursorY)
      .stroke();
    this.cursorY += 10;
  }

  keyValueTable(rows: Array<[string, string]>, headerTitle: string, headerSubtitle: string) {
    const rowH = 22;
    const leftW = Math.round(this.pageWidth * 0.38);
    const rightW = this.pageWidth - leftW;
    for (const [k, v] of rows) {
      this.ensureSpace(rowH + 4, headerTitle, headerSubtitle);
      this.doc.save();
      this.doc.rect(this.doc.page.margins.left, this.cursorY, leftW, rowH).fill(`#${REPORT_THEME.lightBg}`);
      this.doc.rect(this.doc.page.margins.left + leftW, this.cursorY, rightW, rowH).fill("#ffffff");
      this.doc.restore();
      this.doc.rect(this.doc.page.margins.left, this.cursorY, this.pageWidth, rowH).stroke(`#${REPORT_THEME.border}`);
      this.doc.fillColor(`#${REPORT_THEME.text}`).fontSize(10).font("Helvetica-Bold").text(k, this.doc.page.margins.left + 8, this.cursorY + 6, {
        width: leftW - 16,
      });
      this.doc.font("Helvetica").text(v, this.doc.page.margins.left + leftW + 8, this.cursorY + 6, { width: rightW - 16 });
      this.cursorY += rowH;
    }
    this.cursorY += 8;
  }

  gridTable(headers: string[], rows: string[][], colWidths: number[], headerTitle: string, headerSubtitle: string) {
    const rowH = 22;
    this.ensureSpace(rowH * 2, headerTitle, headerSubtitle);
    let x = this.doc.page.margins.left;
    this.doc.save();
    this.doc.rect(this.doc.page.margins.left, this.cursorY, this.pageWidth, rowH).fill(`#${REPORT_THEME.primary}`);
    this.doc.restore();
    headers.forEach((h, idx) => {
      this.doc.fillColor("#ffffff").font("Helvetica-Bold").fontSize(10).text(h, x + 6, this.cursorY + 6, {
        width: colWidths[idx]! - 12,
        ellipsis: true,
      });
      x += colWidths[idx]!;
    });
    this.cursorY += rowH;
    rows.forEach((r) => {
      this.ensureSpace(rowH + 2, headerTitle, headerSubtitle);
      let rowX = this.doc.page.margins.left;
      this.doc.rect(this.doc.page.margins.left, this.cursorY, this.pageWidth, rowH).stroke(`#${REPORT_THEME.border}`);
      r.forEach((c, idx) => {
        this.doc.fillColor(`#${REPORT_THEME.text}`).font("Helvetica").fontSize(9).text(c, rowX + 6, this.cursorY + 6, {
          width: colWidths[idx]! - 12,
          ellipsis: true,
        });
        rowX += colWidths[idx]!;
      });
      this.cursorY += rowH;
    });
    this.cursorY += 8;
  }

  drawPageNumbers() {
    const range = this.doc.bufferedPageRange();
    for (let i = 0; i < range.count; i++) {
      this.doc.switchToPage(range.start + i);
      this.doc
        .font("Helvetica")
        .fontSize(9)
        .fillColor(`#${REPORT_THEME.mutedText}`)
        .text(`Page ${i + 1} of ${range.count}`, this.doc.page.margins.left, this.doc.page.height - 30, {
          width: this.pageWidth,
          align: "right",
        });
    }
  }
}

