import { formatDate, formatTime, type Locale } from "@/lib/utils";
import { buildVerifyQr, mix, reportFooterHtml } from "@/lib/report-html";

/* Printable exam schedule report — the exact design the institution portal
   prints (Portal → Exams → Schedule → Details/Summary report). Shared with
   the member side so students print the identical document. The verification
   QR is injected via `mintQr` (admin-only short-code flow); member prints
   simply omit it. */

export interface ScheduleReportExam {
  id: number;
  name: string;
  nameBn: string | null;
  branchName?: string | null;
  className?: string | null;
  sectionName?: string | null;
  groupName?: string | null;
  departmentName?: string | null;
  shiftName?: string | null;
  startDate: string;
  endDate?: string | null;
}

export interface ScheduleReportPaper {
  subjectName: string | null;
  subjectNameBn: string | null;
  date: string;
  startTime: string;
  endTime: string;
  roomName: string | null;
  roomNameBn: string | null;
  fullMarks: number;
  totalPassMarks: number | null;
  cqMarks?: number | null;
  cqPassMarks?: number | null;
  mcqMarks?: number | null;
  mcqPassMarks?: number | null;
  appliedMarks?: number | null;
  appliedPassMarks?: number | null;
  appliedDate?: string | null;
  note?: string | null;
}

export interface ScheduleReportLabels {
  summaryReport: string;
  detailsReport: string;
  branchLabel: string;
  mainBranch: string;
  classLabel: string;
  sectionLabel: string;
  groupLabel: string;
  departmentLabel: string;
  shiftLabel: string;
  startDate: string;
  endDate: string;
  totalPapers: string;
  subject: string;
  date: string;
  startTime: string;
  endTime: string;
  room: string;
  appliedExamDate: string;
  marksColumn: string;
  fullPass: string;
  appliedShort: string;
  reportTitle: string;
  publishedBadge: string;
  generatedOn: string;
  preparedBy: string;
  approvedBy: string;
  scanToVerify: string;
}

export interface ExamScheduleReportOptions {
  kind: "details" | "summary";
  exam: ScheduleReportExam;
  schedules: ScheduleReportPaper[];
  inst: { name: string; logo?: string | null } | null;
  locale: Locale;
  labels: ScheduleReportLabels;
  /** t.common.note */
  noteLabel: string;
  /** status pill text on the header — pass null on member-facing prints */
  statusText: string | null;
  /** suffix after the status pill (e.g. "Published") */
  publishedBadge?: boolean;
  primary: string;
  accent: string;
  showQr: boolean;
  /** admin-only short-code minter; when omitted or showQr is false, no QR */
  mintQr?: () => Promise<string | null>;
  poweredBy: string;
}

export async function buildExamScheduleReportHtml(opts: ExamScheduleReportOptions): Promise<string> {
  const { kind, exam, schedules: rows, inst, locale, labels: L, noteLabel } = opts;
  const rptPrimary = opts.primary;
  const rptAccent = opts.accent;
  const instName = inst?.name ?? "IncrelogEMS";
  const dash = "—";
  const name = (en: string | null, bn: string | null) => (locale === "bn" && bn ? bn : en ?? dash);
  const part = (full: number | null, pass: number | null) =>
    full != null ? `${full}${pass != null ? ` / ${pass}` : ""}` : dash;

  // theme palette (light combination built from the chosen accents)
  const tint = mix(rptPrimary, "#ffffff", 0.94);
  const tint2 = mix(rptPrimary, "#ffffff", 0.85);
  const soft = mix(rptPrimary, "#ffffff", 0.9);
  const ink = mix(rptPrimary, "#000000", 0.45);

  const kindLabel = kind === "summary" ? L.summaryReport : L.detailsReport;
  const info = [
    [L.branchLabel, exam.branchName ?? L.mainBranch],
    [L.classLabel, exam.className ?? dash],
    [L.sectionLabel, exam.sectionName ?? dash],
    [L.groupLabel, exam.groupName ?? dash],
    [L.departmentLabel, exam.departmentName ?? dash],
    [L.shiftLabel, exam.shiftName ?? dash],
    [`${L.startDate} → ${L.endDate}`, `${formatDate(exam.startDate, locale)}${exam.endDate ? ` → ${formatDate(exam.endDate, locale)}` : ""}`],
    [L.totalPapers, String(rows.length)],
  ];

  // optional verification QR — encodes ONLY the short code (EMS-XXXX-XXXX)
  // so it stays readable at 80x80; the same code prints under the chip and
  // verifies via the project scanner or the public /verify search bar
  let qrDataUrl: string | null = null;
  let qrCodeText: string | null = null;
  if (opts.showQr && opts.mintQr) {
    try {
      const code = await opts.mintQr();
      if (code) {
        qrCodeText = code;
        qrDataUrl = await buildVerifyQr(code, rptPrimary, rptAccent);
      }
    } catch {
      /* report still prints without the QR */
    }
  }

  const initials = instName
    .split(" ")
    .map((w) => w[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const paperRow = (p: ScheduleReportPaper, i: number) => {
    const common = `
        <td style="text-align:center;color:#8a94a6">${i + 1}</td>
        <td style="font-weight:700">${name(p.subjectName, p.subjectNameBn)}</td>
        <td>${formatDate(p.date, locale)}</td>`;
    if (kind === "summary") {
      return `<tr>${common}
          <td>${formatTime(p.startTime, locale)} → ${formatTime(p.endTime, locale)}</td>
          <td>${name(p.roomName, p.roomNameBn)}</td>
          <td>${p.note ?? ""}</td>
        </tr>`;
    }
    return `<tr>${common}
        <td>${p.appliedDate ? formatDate(p.appliedDate, locale) : dash}</td>
        <td>${formatTime(p.startTime, locale)} → ${formatTime(p.endTime, locale)}</td>
        <td>${name(p.roomName, p.roomNameBn)}</td>
        <td style="text-align:center;font-weight:700">${part(p.fullMarks, p.totalPassMarks)}</td>
        <td style="text-align:center">${part(p.cqMarks ?? null, p.cqPassMarks ?? null)}</td>
        <td style="text-align:center">${part(p.mcqMarks ?? null, p.mcqPassMarks ?? null)}</td>
        <td style="text-align:center">${part(p.appliedMarks ?? null, p.appliedPassMarks ?? null)}</td>
        <td>${p.note ?? ""}</td>
      </tr>`;
  };

  const tableHead =
    kind === "summary"
      ? `<tr><th>#</th><th>${L.subject}</th><th>${L.date}</th><th>${L.startTime} → ${L.endTime}</th><th>${L.room}</th><th>${noteLabel}</th></tr>`
      : `<tr><th>#</th><th>${L.subject}</th><th>${L.date}</th><th>${L.appliedExamDate}</th><th>${L.startTime} → ${L.endTime}</th><th>${L.room}</th>
         <th>${L.marksColumn} (${L.fullPass})</th><th>CQ (${L.fullPass})</th><th>MCQ (${L.fullPass})</th><th>${L.appliedShort} (${L.fullPass})</th><th>${noteLabel}</th></tr>`;

  const footer = reportFooterHtml({
    primary: rptPrimary,
    accent: rptAccent,
    qrDataUrl,
    codeText: qrCodeText,
    scanLabel: L.scanToVerify,
    poweredBy: opts.poweredBy,
    reportLabel: `${L.reportTitle} — ${kindLabel}`,
  });

  return `<!DOCTYPE html>
<html lang="${locale}">
<head>
<meta charset="utf-8"/>
<title>${L.reportTitle} — ${exam.name}</title>
<style>
  * { box-sizing: border-box; }
  html, body { margin: 0; padding: 0; }
  body {
    font-family: 'Montserrat', 'Noto Sans Bengali', sans-serif;
    color: #2c323f; background: #ffffff; padding: 26px 28px;
    -webkit-print-color-adjust: exact; print-color-adjust: exact;
  }
  @page { size: A4; margin: 10mm; }

  /* ---- light header band (accent kept via the side bar + kicker) ---- */
  .hdr {
    position: relative; overflow: hidden; border-radius: 14px;
    background: linear-gradient(180deg, ${soft} 0%, #ffffff 78%);
    border: 1px solid ${tint2};
    padding: 22px 26px 20px 30px; display: flex; align-items: center; gap: 18px;
  }
  .hdr::before {
    content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 6px;
    background: linear-gradient(180deg, ${rptPrimary} 0%, ${rptAccent} 100%);
  }
  .hdr::after {
    content: ""; position: absolute; right: -52px; top: -52px; width: 190px; height: 190px;
    border-radius: 50%; background: ${rptAccent}; opacity: 0.08;
  }
  .logo {
    width: 56px; height: 56px; border-radius: 13px; background: #ffffff;
    border: 1px solid ${tint2}; box-shadow: 0 2px 8px rgba(44,50,63,0.05);
    display: flex; align-items: center; justify-content: center; overflow: hidden;
    flex: 0 0 auto; position: relative; z-index: 1;
  }
  .logo img { max-width: 100%; max-height: 100%; object-fit: contain; }
  .logo span { font-size: 18px; font-weight: 800; letter-spacing: 1px; color: ${rptPrimary}; }
  .hb { flex: 1; min-width: 0; position: relative; z-index: 1; }
  .kick {
    margin: 0 0 4px; font-size: 10px; font-weight: 800; letter-spacing: 2.6px;
    text-transform: uppercase; color: ${rptAccent};
  }
  .hb h1 { margin: 0; font-size: 21px; font-weight: 800; letter-spacing: 0.3px; color: #2c323f; }
  .exam { margin: 5px 0 0; font-size: 13px; color: ${ink}; }
  .hs { text-align: right; position: relative; z-index: 1; flex: 0 0 auto; }
  .pill {
    display: inline-block; background: ${tint}; color: ${ink}; border: 1px solid ${tint2};
    border-radius: 999px; padding: 4px 14px; font-size: 11px; font-weight: 700; letter-spacing: 0.4px;
  }
  .gen { display: block; margin-top: 7px; font-size: 10px; color: #98a1b3; }

  /* thin accent rule under the header */
  .bar { height: 3px; border-radius: 0 0 8px 8px; margin: -1px 10px 18px 0;
    background: linear-gradient(90deg, ${rptPrimary} 0%, ${rptAccent} 60%, transparent 100%); }

  /* ---- exam info chips ---- */
  .meta { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 18px; }
  .chip {
    background: #ffffff; border: 1px solid ${tint2}; border-left: 3px solid ${rptAccent};
    border-radius: 9px; padding: 6px 12px 7px; min-width: 128px;
  }
  .chip span { display: block; font-size: 9px; font-weight: 700; letter-spacing: 1px;
    text-transform: uppercase; color: ${ink}; margin-bottom: 1px; }
  .chip b { font-size: 12px; font-weight: 700; color: #2c323f; }

  h2.sect {
    font-size: 12px; font-weight: 800; letter-spacing: 1.6px; text-transform: uppercase;
    color: ${ink}; margin: 0 0 8px; display: flex; align-items: center; gap: 8px;
  }
  h2.sect::after { content: ""; flex: 1; height: 1px; background: ${tint2}; }

  /* ---- schedule table (light) ---- */
  table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
  th, td { border: 1px solid ${tint2}; padding: 7px 9px; }
  thead th {
    background: ${tint}; color: ${ink}; text-align: left; font-size: 10px;
    font-weight: 800; letter-spacing: 0.7px; text-transform: uppercase;
    border-bottom: 2px solid ${rptAccent};
  }
  tbody tr:nth-child(even) { background: ${mix(rptPrimary, "#ffffff", 0.97)}; }
  tfoot td { background: ${soft}; font-weight: 700; }

  /* ---- signatures ---- */
  .sig { display: flex; align-items: flex-end; justify-content: space-around; margin-top: 34px; gap: 24px; }
  .line { text-align: center; flex: 0 0 auto; }
  .line i { display: block; width: 190px; border-bottom: 1.5px dotted #9aa4b5; height: 26px; }
  .line span { font-size: 11px; font-weight: 700; color: #525f7f; }
</style>
</head>
<body>
  <div class="hdr">
    <div class="logo">${inst?.logo ? `<img src="${inst.logo}" alt=""/>` : `<span>${initials}</span>`}</div>
    <div class="hb">
      <p class="kick">${L.reportTitle} · ${kindLabel}</p>
      <h1>${instName}</h1>
      <p class="exam">${exam.name}${exam.nameBn && locale === "bn" ? ` (${exam.nameBn})` : ""}</p>
    </div>
    <div class="hs">
      ${opts.statusText ? `<span class="pill">${opts.statusText}${opts.publishedBadge ? ` · ${L.publishedBadge}` : ""}</span>` : ""}
      <span class="gen">${L.generatedOn}: ${formatDate(new Date().toISOString(), locale)}</span>
    </div>
  </div>
  <div class="bar"></div>

  <div class="meta">${info.map(([k, v]) => `<div class="chip"><span>${k}</span><b>${v}</b></div>`).join("")}</div>

  <h2 class="sect">${kindLabel}</h2>
  <table>
    <thead>${tableHead}</thead>
    <tbody>${rows.map(paperRow).join("")}</tbody>
    <tfoot><tr><td colspan="${kind === "summary" ? 5 : 10}" style="text-align:right">${L.totalPapers}</td><td style="text-align:center">${rows.length}</td></tr></tfoot>
  </table>

  <div class="sig">
    <div class="line"><i></i><span>${L.preparedBy}</span></div>
    <div class="line"><i></i><span>${L.approvedBy}</span></div>
  </div>

  ${footer}
</body>
</html>`;
}
