"use client";

import QRCodeStyling from "qr-code-styling";
import { increlogLogoSvgString } from "@/components/IncrelogLogo";

/* Shared building blocks for the printable institution reports (exam
   schedule, inventory, …): the marksheet-style color presets, tint helper,
   scanner-first verification QR and the branded footer (static Increlog
   logo + "Developed by Increlog Unified Solutions" + optional verify QR). */

/** blend color `a` toward `b`; amount is the portion of `b` (0-1) */
export function mix(a: string, b: string, amount: number): string {
  const hex = (c: string) => {
    const h = c.replace("#", "");
    const v = h.length === 3 ? h.split("").map((x) => x + x).join("") : h;
    return [parseInt(v.slice(0, 2), 16), parseInt(v.slice(2, 4), 16), parseInt(v.slice(4, 6), 16)];
  };
  const [r1, g1, b1] = hex(a);
  const [r2, g2, b2] = hex(b);
  const f = (x: number, y: number) => Math.max(0, Math.min(255, Math.round(x + (y - x) * amount)));
  return "#" + [f(r1, r2), f(g1, g2), f(b1, b2)].map((x) => x.toString(16).padStart(2, "0")).join("");
}

/** report color presets — same palette family as the marksheet themes */
export const REPORT_PRESETS = [
  { primary: "#24695c", accent: "#c9a227" }, // teal & gold
  { primary: "#1e5a8a", accent: "#e39a1e" }, // blue & amber
  { primary: "#7a1f2b", accent: "#c9a227" }, // maroon & gold
  { primary: "#2e6b3e", accent: "#b87333" }, // green & copper
  { primary: "#3f3d8a", accent: "#b0446e" }, // indigo & rose
];

/** Scanner-first verification QR (solid dark modules on white, quiet zone),
    tinted from the report theme. Returns a PNG data URL (safe to embed in
    the print popup and in print output) or null on failure. */
export async function buildVerifyQr(data: string, primary: string, accent: string): Promise<string | null> {
  try {
    const qr = new QRCodeStyling({
      width: 320,
      height: 320,
      margin: 14,
      data,
      backgroundOptions: { color: "#ffffff" },
      dotsOptions: { type: "rounded", color: mix(primary, "#000000", 0.55) },
      cornersSquareOptions: { type: "extra-rounded", color: mix(primary, "#000000", 0.55) },
      cornersDotOptions: { type: "dot", color: accent },
    });
    const blob = (await qr.getRawData("png")) as Blob | null;
    if (!blob) return null;
    return await new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(String(reader.result));
      reader.onerror = () => resolve("");
      reader.readAsDataURL(blob);
    });
  } catch {
    return null;
  }
}

/** Branded report footer: static Increlog logo + "Developed by Increlog
    Unified Solutions", with the verification QR (when provided) on the
    right. The QR encodes ONLY the short code (codeText) — also printed
    under the chip so anyone can type it into the public /verify page.
    Embed inside the report <body> — all styles are inline. */
export function reportFooterHtml({
  primary,
  accent,
  qrDataUrl,
  codeText,
  scanLabel,
  poweredBy,
  reportLabel,
}: {
  primary: string;
  accent: string;
  qrDataUrl?: string | null;
  codeText?: string | null;
  scanLabel: string;
  poweredBy: string;
  reportLabel: string;
}): string {
  const qrBlock = qrDataUrl
    ? `<td style="text-align:right;vertical-align:middle">
        <table style="border-collapse:collapse;margin-left:auto"><tr>
          <td style="padding-right:10px;vertical-align:middle">
            <span style="display:block;font-size:9px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:${primary}">${scanLabel}</span>
            <span style="display:block;font-size:8px;color:#9aa5b1;margin-top:2px">${reportLabel}</span>
          </td>
          <td style="vertical-align:middle">
            <div style="width:80px;height:80px;border:1px solid ${mix(primary, "#ffffff", 0.75)};border-radius:10px;padding:4px;background:#ffffff">
              <img src="${qrDataUrl}" alt="QR" style="width:72px;height:72px;display:block"/>
            </div>
            ${codeText ? `<div style="margin-top:3px;font:600 8.5px Rubik,Consolas,monospace;letter-spacing:.5px;color:${primary};text-align:center">${codeText}</div>` : ""}
          </td>
        </tr></table>
      </td>`
    : "";
  return `<table style="width:100%;border-collapse:collapse;margin-top:26px"><tr>
    <td style="vertical-align:middle;padding-top:12px;border-top:2px solid ${mix(accent, "#ffffff", 0.25)}">
      <div style="display:flex;align-items:center;gap:8px">
        ${increlogLogoSvgString(26)}
        <span style="font-size:9.5px;color:#8a94a6;letter-spacing:.3px">${poweredBy}</span>
      </div>
      <span style="display:block;margin-top:4px;font-size:8.5px;color:#b3bac6">${reportLabel}</span>
    </td>
    ${qrBlock}
  </tr></table>`;
}
