import jsPDF from "jspdf";
import { loadImageAsDataURL } from "@/lib/reportCover";
import acmLogoFull from "@/assets/acm-logo-full.png";

/**
 * Shared branded header/footer for every accounting report PDF, so all reports
 * match the "main report" look: logo top-left, centered title + optional
 * subtitle, optional left-aligned meta lines, and a "Generated … / Page X of Y"
 * footer on every page.
 *
 * The logo load is async (canvas → dataURL), so callers preload it once via
 * `loadBrandedLogo()` and pass the result into the sync `drawBrandedHeader()`.
 * Falls back to the management-company (ACM) logo when no association logo is set.
 */

const MUTED: [number, number, number] = [110, 116, 122];

export type BrandedLogo = { dataURL: string; w: number; h: number };

/** Preload the association logo (ACM fallback) as a dataURL for PDF embedding. */
export async function loadBrandedLogo(logoUrl?: string | null): Promise<BrandedLogo | null> {
  const url = logoUrl || (acmLogoFull as unknown as string);
  const img = await loadImageAsDataURL(url, "png");
  if (img) return { dataURL: img.dataURL, w: img.w, h: img.h };
  // Fall back to the bundled ACM logo if the association logo failed to load.
  if (logoUrl) {
    const fallback = await loadImageAsDataURL(acmLogoFull as unknown as string, "png");
    if (fallback) return { dataURL: fallback.dataURL, w: fallback.w, h: fallback.h };
  }
  return null;
}

export type BrandedHeaderOpts = {
  logo?: BrandedLogo | null;
  title: string;
  subtitle?: string;
  /** Optional bold-label / value lines under the title (e.g. account, period). */
  metaLines?: { label: string; value: string }[];
};

/** Draws the branded header on the current page; returns the y to start the body. */
export function drawBrandedHeader(doc: jsPDF, opts: BrandedHeaderOpts): number {
  const W = doc.internal.pageSize.getWidth();
  const ML = 40;

  if (opts.logo) {
    try {
      const h = 46;
      const w = Math.min(170, h * (opts.logo.w / opts.logo.h));
      doc.addImage(opts.logo.dataURL, "PNG", ML, 28, w, h, undefined, "FAST");
    } catch { /* ignore logo failures */ }
  }

  doc.setFont("helvetica", "bold"); doc.setFontSize(18); doc.setTextColor(20);
  doc.text(opts.title, W / 2, 52, { align: "center" });
  let headerBottom = 60;
  if (opts.subtitle) {
    doc.setFont("helvetica", "normal"); doc.setFontSize(11); doc.setTextColor(90);
    doc.text(opts.subtitle, W / 2, 70, { align: "center" });
    headerBottom = 74;
  }

  let y = Math.max(headerBottom, 88) + 6;
  if (opts.metaLines?.length) {
    doc.setFontSize(10);
    for (const m of opts.metaLines) {
      doc.setFont("helvetica", "bold"); doc.setTextColor(20);
      doc.text(m.label, ML, y);
      const lw = doc.getTextWidth(m.label);
      doc.setFont("helvetica", "normal");
      doc.text(` ${m.value}`, ML + lw, y);
      y += 14;
    }
    y += 4;
  }
  return y;
}

/** Draws "Generated … / Page X of Y" on every page. Call once after the body. */
export function drawBrandedFooter(doc: jsPDF): void {
  const W = doc.internal.pageSize.getWidth();
  const H = doc.internal.pageSize.getHeight();
  const ML = 40;
  const total = doc.getNumberOfPages();
  const gen = new Date().toLocaleString("en-US");
  for (let p = 1; p <= total; p++) {
    doc.setPage(p);
    doc.setFont("helvetica", "normal"); doc.setFontSize(8); doc.setTextColor(...MUTED);
    doc.text(`Generated ${gen}`, ML, H - 24);
    doc.text(`Page ${p} of ${total}`, W - ML, H - 24, { align: "right" });
  }
}
