import { formatDate, type Locale } from "@/lib/utils";
import { DEFAULT_ACCENT, DEFAULT_PRIMARY, brandFooter, esc, instLogoChip, themeShades, type InstBranding } from "@/lib/print";

/* Student ID card builder — the exact 4 designs the institution portal prints
   (Certificates → ID Card). The member side renders the same HTML so students
   see their card exactly as the institution produces it. */

export type DesignId = 1 | 2 | 3 | 4;

export type IdFieldKey =
  | "roll" | "className" | "section" | "shift" | "group"
  | "dob" | "gender" | "guardian" | "phone" | "address" | "studentId"
  | "cardNo" | "registrationNo" | "bloodGroup" | "validTill";

export const DEFAULT_ID_FIELDS: Record<IdFieldKey, boolean> = {
  roll: true,
  className: true,
  section: true,
  shift: false,
  group: false,
  dob: true,
  gender: false,
  guardian: false,
  phone: false,
  address: false,
  studentId: true,
  cardNo: false,
  registrationNo: false,
  bloodGroup: false,
  validTill: false,
};

export interface IdCardStudent {
  id: number;
  roll: string;
  name: string;
  nameBn: string | null;
  gender: string;
  dob: string | null;
  guardianName: string;
  guardianPhone: string;
  address: string | null;
  className: string | null;
  sectionName: string | null;
  shiftName: string | null;
  groupName: string | null;
  cardNo: string | null;
  registrationNo: string | null;
  bloodGroup: string | null;
  cardValidTill: string | null;
}

export interface IdCardLabels {
  studentIdCard: string;
  fRoll: string;
  fClass: string;
  fSection: string;
  fShift: string;
  fGroup: string;
  fDob: string;
  fGender: string;
  fGuardian: string;
  fPhone: string;
  fAddress: string;
  fId: string;
  fCardNo: string;
  fRegistration: string;
  fBlood: string;
  fValidTill: string;
  male: string;
  female: string;
}

export interface IdCardOptions {
  st: IdCardStudent;
  inst: InstBranding | null;
  design: DesignId;
  primary?: string;
  accent?: string;
  fields: Record<IdFieldKey, boolean>;
  labels: IdCardLabels;
  locale: Locale;
}

/** printed fields, honoring the same on/off toggles as the portal */
function idFieldRows(st: IdCardStudent, fields: Record<IdFieldKey, boolean>, L: IdCardLabels, locale: Locale): [string, string][] {
  const rows: [string, string][] = [];
  const push = (on: boolean, k: string, v: string | null | undefined) => {
    if (on) rows.push([k, v ?? "—"]);
  };
  push(fields.roll, L.fRoll, st.roll);
  push(fields.className, L.fClass, st.className);
  push(fields.section, L.fSection, st.sectionName);
  push(fields.shift, L.fShift, st.shiftName);
  push(fields.group, L.fGroup, st.groupName);
  push(fields.dob, L.fDob, st.dob ? formatDate(st.dob, locale) : null);
  push(fields.gender, L.fGender, st.gender === "MALE" ? L.male : st.gender === "FEMALE" ? L.female : st.gender);
  push(fields.guardian, L.fGuardian, st.guardianName);
  push(fields.phone, L.fPhone, st.guardianPhone);
  push(fields.address, L.fAddress, st.address);
  push(fields.studentId, L.fId, `EMS-${String(st.id).padStart(5, "0")}`);
  // identity data maintained on the Student Identity page (optional fields)
  push(fields.cardNo, L.fCardNo, st.cardNo);
  push(fields.registrationNo, L.fRegistration, st.registrationNo);
  push(fields.bloodGroup, L.fBlood, st.bloodGroup);
  push(fields.validTill, L.fValidTill, st.cardValidTill ? formatDate(st.cardValidTill, locale) : null);
  return rows;
}

/** Build one ID card (all 4 designs, same HTML as the portal print). */
export function idCardHtml(o: IdCardOptions): string {
  const { st, inst, design, fields, labels: L, locale } = o;
  if (!st || !inst) return "";
  const primary = o.primary ?? DEFAULT_PRIMARY;
  const accent = o.accent ?? DEFAULT_ACCENT;
  const { dark, tint, accentDark, accentTint } = themeShades(primary, accent);
  const initials = esc(st.name.split(" ").map((w) => w[0]).slice(0, 2).join("").toUpperCase());
  const nm = esc(locale === "bn" && st.nameBn ? st.nameBn : st.name);
  const rows = idFieldRows(st, fields, L, locale);
  const fieldRow = (k: string, v: string) =>
    `<tr><td style="padding:1.5px 0;font-size:9.5px;color:#718096;white-space:nowrap;padding-right:8px">${esc(k)}</td><td style="padding:1.5px 0;font-size:10.5px;font-weight:600">${esc(v)}</td></tr>`;

  if (design === 1) {
    // Classic — landscape, light tinted band, left avatar
    return `
<div style="width:336px;height:212px;border-radius:12px;overflow:hidden;border:1px solid #d9e1ec;box-shadow:0 6px 18px rgba(0,0,0,.12);display:flex;flex-direction:column;background:#fff;font-family:inherit">
  <div style="background:${tint};border-bottom:2px solid ${primary};padding:8px 14px;display:flex;align-items:center;gap:8px">
    ${instLogoChip(inst.logo, 30)}
    <div style="min-width:0">
      <p style="margin:0;font-size:12px;font-weight:700;color:${dark};white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(inst.name)}</p>
      <p style="margin:0;font-size:7.5px;color:${primary};letter-spacing:1px">${esc(L.studentIdCard).toUpperCase()}</p>
    </div>
  </div>
  <div style="display:flex;gap:14px;padding:12px 16px;flex:1">
    <div style="text-align:center;flex:0 0 auto">
      <div style="width:76px;height:76px;border-radius:50%;background:${tint};color:${primary};display:flex;align-items:center;justify-content:center;font-size:24px;font-weight:700;border:2px solid ${primary}55">${initials}</div>
      <p style="margin:6px 0 0;font-size:11px;font-weight:700;max-width:90px">${nm}</p>
    </div>
    <div style="flex:1;overflow:hidden">
      <table style="width:100%">${rows.map(([k, v]) => fieldRow(k, v)).join("")}</table>
    </div>
  </div>
  <div style="background:${primary};height:8px"></div>
</div>`;
  }
  if (design === 2) {
    // Modern — portrait, light tinted header block, centered
    return `
<div style="width:212px;height:336px;border-radius:14px;overflow:hidden;border:1px solid #d9e1ec;box-shadow:0 6px 18px rgba(0,0,0,.12);background:#fff;font-family:inherit;text-align:center">
  <div style="background:${tint};border-bottom:2px solid ${primary};padding:12px 10px 34px">
    ${instLogoChip(inst.logo, 30)}
    <p style="margin:6px 0 0;font-size:11px;font-weight:700;color:${dark}">${esc(inst.name)}</p>
    <p style="margin:0;font-size:7px;color:${primary};letter-spacing:1.5px">${esc(L.studentIdCard).toUpperCase()}</p>
  </div>
  <div style="margin-top:-26px">
    <div style="width:64px;height:64px;border-radius:50%;background:${tint};color:${primary};display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:700;border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.18);margin:0 auto">${initials}</div>
    <p style="margin:6px 0 0;font-size:12px;font-weight:700">${nm}</p>
  </div>
  <div style="text-align:left;padding:8px 16px">
    <table style="width:100%">${rows.map(([k, v]) => fieldRow(k, v)).join("")}</table>
  </div>
  <div style="border-top:2px solid ${primary};margin:6px 14px 0;padding-top:5px;font-size:7.5px;color:#718096">${esc(inst.phone)}</div>
</div>`;
  }
  if (design === 3) {
    // Side Rail — landscape, vertical tinted rail
    return `
<div style="width:336px;height:212px;border-radius:12px;overflow:hidden;border:1px solid #d9e1ec;box-shadow:0 6px 18px rgba(0,0,0,.12);display:flex;background:#fff;font-family:inherit">
  <div style="background:${tint};border-right:2px solid ${primary};width:56px;display:flex;flex-direction:column;align-items:center;padding:10px 0;gap:10px">
    <div style="width:14px;height:14px;border-radius:50%;background:${primary};border:3px solid ${primary}55"></div>
    <div style="color:${dark};font-size:8px;font-weight:700;letter-spacing:2px;writing-mode:vertical-rl;text-orientation:mixed;flex:1">${esc(inst.name).toUpperCase()}</div>
    <div style="color:${primary};font-size:6.5px;letter-spacing:1px;writing-mode:vertical-rl">ID</div>
  </div>
  <div style="flex:1;padding:12px 14px;min-width:0">
    <p style="margin:0;font-size:8.5px;color:${primary};font-weight:700;letter-spacing:2px">${esc(L.studentIdCard).toUpperCase()}</p>
    <div style="display:flex;gap:10px;margin-top:8px">
      <div style="width:58px;height:58px;border-radius:10px;background:${tint};color:${primary};display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;flex:0 0 auto">${initials}</div>
      <div style="min-width:0">
        <p style="margin:0;font-size:12.5px;font-weight:700;word-break:break-word">${nm}</p>
        <table style="margin-top:3px">${rows.map(([k, v]) => fieldRow(k, v)).join("")}</table>
      </div>
    </div>
  </div>
</div>`;
  }
  // 4 — Elegant Frame — portrait, double border (primary + accent)
  return `
<div style="width:212px;height:336px;background:#fff;box-shadow:0 6px 18px rgba(0,0,0,.12);font-family:inherit;text-align:center;padding:7px">
  <div style="border:2px solid ${accent};border-radius:8px;height:100%;padding:4px">
    <div style="border:1.5px solid ${primary};border-radius:6px;height:100%;padding:8px 10px;box-sizing:border-box;overflow:hidden">
      <div style="background:${accentTint};border-bottom:1px solid ${accent}88;margin:0 -10px 8px;padding:8px 10px 7px">
        ${instLogoChip(inst.logo, 28)}
        <p style="margin:4px 0 0;font-size:10.5px;font-weight:700;color:${dark}">${esc(inst.name)}</p>
        <p style="margin:0;font-size:7px;font-weight:700;color:${accentDark};letter-spacing:2px">${esc(L.studentIdCard).toUpperCase()}</p>
      </div>
      <div style="width:58px;height:58px;border-radius:50%;border:2px solid ${accent};color:${primary};display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;margin:0 auto">${initials}</div>
      <p style="margin:6px 0;font-size:12px;font-weight:700">${nm}</p>
      <div style="border-top:1px solid ${accent}88;margin:0 8px 6px"></div>
      <div style="text-align:left">
        <table style="width:100%">${rows.map(([k, v]) => fieldRow(k, v)).join("")}</table>
      </div>
    </div>
  </div>
</div>`;
}

/** rows of cards exactly like the portal print (2-up landscape, 3-up portrait) */
export function idCardPrintHtml(cards: string[], design: DesignId, poweredBy: string): string {
  const perRow = design === 2 || design === 4 ? 3 : 2;
  const rows: string[] = [];
  for (let i = 0; i < cards.length; i += perRow) rows.push(cards.slice(i, i + perRow).join(""));
  return rows
    .map(
      (r, i) =>
        `<div${i < rows.length - 1 ? ' style="page-break-after:always"' : ""}><div style="display:flex;justify-content:center;gap:14px;padding:6px 0">${r}</div>${brandFooter(poweredBy)}</div>`,
    )
    .join("");
}
