"use client";

import type { CSSProperties } from "react";
import type { Locale } from "@/lib/utils";
import { mix } from "@/lib/print";
import type { SheetRow } from "@/lib/result-sheet";

/* The institution's official printed marksheet card (Portal → Exam Results →
   Single format). One shared component so the member-facing (/me) print is
   pixel-identical to the office copy — styling lives in increlog.css
   (.ems-mks*), which both print paths inline. */

export type MksFieldKey =
  | "photo" | "father" | "mother" | "roll" | "className" | "section" | "shift" | "session" | "attendance" | "progress";

export const DEFAULT_MKS_FIELDS: Record<MksFieldKey, boolean> = {
  photo: true, father: true, mother: true, roll: true, className: true,
  section: true, shift: true, session: true, attendance: true, progress: true,
};

/** academic session text on the sheet: "2026-27" from the exam start year */
export function sessionLabelText(startIso: string | Date | null | undefined, now = new Date()): string {
  const y = startIso ? new Date(startIso).getFullYear() : now.getFullYear();
  return `${y}-${String(y + 1).slice(2)}`;
}

/** derived color palette consumed by the .ems-mks styles via CSS variables */
export function mksThemeVars(primary: string, accent: string): CSSProperties {
  return {
    "--ems-primary": primary,
    "--ems-accent": accent,
    "--ems-tint": mix(primary, "#ffffff", 0.88),
    "--ems-tint-soft": mix(primary, "#ffffff", 0.94),
    "--ems-dark": mix(primary, "#000000", 0.34),
    "--ems-primary-25": mix(primary, "#ffffff", 0.75),
    "--ems-primary-33": mix(primary, "#ffffff", 0.67),
    "--ems-primary-55": mix(primary, "#ffffff", 0.45),
    "--ems-present-tint": mix(primary, "#ffffff", 0.88),
    "--ems-present-text": mix(primary, "#000000", 0.42),
    "--ems-present-border": mix(primary, "#ffffff", 0.68),
    "--ems-absent-tint": mix(accent, "#ffffff", 0.86),
    "--ems-absent-text": mix(accent, "#000000", 0.52),
    "--ems-absent-border": mix(accent, "#ffffff", 0.62),
  } as CSSProperties;
}

export interface ExamSheetLabels {
  fatherLabel: string;
  motherLabel: string;
  roll: string;
  classLabel: string;
  fieldNameSection: string;
  fieldNameShift: string;
  sessionLabel: string;
  scanToVerify: string;
  subject: string;
  examColLabel: string;
  periodicalExamColLabel: string;
  marksCol: string;
  highestCol: string;
  statusCol: string;
  failed: string;
  passed: string;
  total: string;
  meritPos: string;
  academicDay: string;
  present: string;
  absent: string;
  progress: string;
  good: string;
  needImprovement: string;
  bad: string;
  signTeacher: string;
  signGuardian: string;
  signPrincipal: string;
  authorization: string;
  activities: string;
  developedBy: string;
}

export interface ExamSheetCardProps {
  row: SheetRow;
  inst: { name: string; address?: string | null; phone?: string | null; logo?: string | null } | null;
  /** the (single) exam identity — null on aggregate sheets */
  exam: { name: string; nameBn: string | null } | null;
  /** resolved class text (exam's class name, or the class item on aggregates) */
  classText: string;
  /** aggregate formats: per-exam side-by-side columns */
  aggregateExamNames?: { name: string; nameBn: string | null }[] | null;
  /** show the CQ/MCQ/Applied part columns (portal's showParts && hasAnyPart) */
  partsColumns?: boolean;
  /** verification QR image (data/object URL) for this student */
  qr?: string | null;
  visibleFields: Record<MksFieldKey, boolean>;
  principalSig?: string | null;
  teacherSig?: string | null;
  teacherName?: string | null;
  principalName?: string | null;
  sessionText: string;
  labels: ExamSheetLabels;
  locale: Locale;
  /** locale-aware digits (Bangla numerals in bn) */
  num: (v: string | number) => string;
  themeVars?: CSSProperties;
}

export default function ExamSheetCard({
  row: r,
  inst,
  exam,
  classText,
  aggregateExamNames,
  partsColumns = false,
  qr = null,
  visibleFields,
  principalSig,
  teacherSig,
  teacherName,
  principalName,
  sessionText,
  labels: L,
  locale,
  num,
  themeVars,
}: ExamSheetCardProps) {
  const isAggregate = !!aggregateExamNames;
  const examCount = isAggregate ? aggregateExamNames!.length : 0;

  return (
    <div className="card p-3 ems-mks-card" style={{ borderColor: "#e6edef" }}>
      <div className="ems-mks" style={themeVars}>

        {/* Header: logo | institution info | student photo + verify QR */}
        <div className="ems-mks-header">
          {inst?.logo ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={inst.logo} className="ems-mks-logo" alt="" />
          ) : (
            // eslint-disable-next-line @next/next/no-img-element
            <img src="/assets/images/increlog-logo.png" alt="Increlog" width={62} height={62} draggable={false} style={{ height: 62, width: "auto" }} />
          )}
          <div className="ems-mks-school">
            <h5>{inst?.name}</h5>
            {inst?.address && <p className="addr">{inst.address}</p>}
            {inst?.phone && <p className="contact">{inst.phone}</p>}
          </div>
          {visibleFields.photo &&
            (r.photoUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={r.photoUrl} className="ems-mks-photo" alt="" />
            ) : (
              <div className="ems-mks-photo">
                {r.name.split(" ").map((w) => w[0]).slice(0, 2).join("").toUpperCase()}
              </div>
            ))}
        </div>

        {/* Student details — name banner, guardian band, ID-card field grid.
            Exam identity (name/type/dates) is shown on the merit list
            sheet only — never on individual result sheets. */}
        <div className="ems-mks-body">
          <div className="ems-mks-info">
            <div className="ems-mks-name">
              {locale === "bn" && r.nameBn ? r.nameBn : r.name}
            </div>
            {(visibleFields.father || visibleFields.mother) && (
              <div className="ems-mks-guardian">
                {visibleFields.father && (
                  <span>
                    <strong>{L.fatherLabel}:</strong>{" "}
                    {((locale === "bn" && r.guardianNameBn) || r.guardianName) ?? "—"}
                  </span>
                )}
                {visibleFields.father && visibleFields.mother && <span> &nbsp;·&nbsp; </span>}
                {visibleFields.mother && (
                  <span>
                    <strong>{L.motherLabel}:</strong>{" "}
                    {((locale === "bn" && r.motherNameBn) || r.motherName) ?? "—"}
                  </span>
                )}
              </div>
            )}
            <div className="ems-mks-fields">
              {visibleFields.roll && (
                <div className="f">
                  <span className="k">{L.roll}</span>
                  <span className="v">{num(r.roll)}</span>
                </div>
              )}
              {visibleFields.className && (
                <div className="f">
                  <span className="k">{L.classLabel}</span>
                  <span className="v">{classText}</span>
                </div>
              )}
              {visibleFields.section && (
                <div className="f">
                  <span className="k">{L.fieldNameSection}</span>
                  <span className="v">
                    {(locale === "bn" && r.sectionNameBn ? r.sectionNameBn : r.sectionName) ?? "—"}
                  </span>
                </div>
              )}
              {visibleFields.shift && (
                <div className="f">
                  <span className="k">{L.fieldNameShift}</span>
                  <span className="v">
                    {(locale === "bn" && r.shiftNameBn ? r.shiftNameBn : r.shiftName) ?? "—"}
                  </span>
                </div>
              )}
              {visibleFields.session && (
                <div className="f">
                  <span className="k">{L.sessionLabel}</span>
                  <span className="v">{num(sessionText)}</span>
                </div>
              )}
            </div>
          </div>

          {/* verification QR — right column beside the student info */}
          <div className="ems-mks-qr">
            {qr ? (
              <>
                <div className="qr-frame">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={qr} alt="verify" />
                </div>
                <p className="cap mb-0">{L.scanToVerify}</p>
                {r.verifyCode && (
                  <p className="cap mb-0" style={{ fontFamily: "Rubik, Consolas, monospace", fontWeight: 600 }}>
                    {r.verifyCode}
                  </p>
                )}
              </>
            ) : (
              <span className="ems-fs-11 text-muted">QR…</span>
            )}
          </div>
        </div>

        {/* Marks table — Subject | exam columns | Marks | Highest | Status */}
        <table className="ems-mks-table">
          <thead>
            <tr>
              <th rowSpan={2} className="subject">
                {L.subject}
              </th>
              <th colSpan={examCount || 1} style={{ height: 23 }}>
                {isAggregate ? L.periodicalExamColLabel : L.examColLabel}
              </th>
              <th rowSpan={2}>{L.marksCol}</th>
              <th rowSpan={2}>{L.highestCol}</th>
              <th rowSpan={2}>{L.statusCol}</th>
            </tr>
            <tr>
              {(isAggregate
                ? aggregateExamNames!.map((e) => (locale === "bn" && e.nameBn ? e.nameBn : e.name))
                : [exam ? (locale === "bn" && exam.nameBn ? exam.nameBn : exam.name) : "—"]
              ).map((name, i) => (
                <th key={i} style={{ height: 23 }}>
                  {name}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {r.subjects.map((sub) => (
              <tr key={sub.scheduleId}>
                <td className="subject">
                  {locale === "bn" && sub.subjectBn ? sub.subjectBn : sub.subject}
                </td>
                {(isAggregate
                  ? sub.perExam ?? [sub.obtained]
                  : partsColumns
                    ? [sub.cq, sub.mcq, sub.applied]
                    : [sub.obtained]
                ).map((v, i) => (
                  <td key={i}>
                    {v !== null && v !== undefined ? (
                      <span className="score">{num(v)}</span>
                    ) : (
                      <span className="text-muted">—</span>
                    )}
                  </td>
                ))}
                <td className="f-w-800">
                  {sub.obtained !== null ? num(sub.obtained) : "—"}
                  <span className="text-muted f-w-500">/{num(sub.full)}</span>
                </td>
                <td>{sub.highest != null ? num(sub.highest) : "—"}</td>
                <td>
                  {sub.obtained === null ? (
                    <span className="text-muted">—</span>
                  ) : sub.failed ? (
                    <span className="fail">{L.failed}</span>
                  ) : (
                    <span className="pass">{L.passed}</span>
                  )}
                </td>
              </tr>
            ))}
            <tr className="total-row">
              <td>{L.total}</td>
              {Array.from({ length: isAggregate ? Math.max(examCount, 1) : 1 }).map((_, i) => (
                <td key={i} className="text-muted">
                  –
                </td>
              ))}
              <td>
                {num(r.totalObtained)}
                <span className="text-muted f-w-500">/{num(r.totalFull)}</span>
              </td>
              <td>–</td>
              <td></td>
            </tr>
          </tbody>
        </table>

        {/* Merit */}
        <table className="ems-mks-merit">
          <tbody>
            <tr>
              <td className="lbl">{L.meritPos}</td>
              <td className="f-w-800">{r.position === null ? "—" : num(r.position)}</td>
            </tr>
          </tbody>
        </table>

        {/* Attendance */}
        {visibleFields.attendance && (
          <>
            <div className="ems-mks-att-row">
              <div className="ems-mks-att-lbl ems-mks-att-academic">
                {L.academicDay}
              </div>
              <div className="ems-mks-att-val ems-mks-att-academic">
                {num(r.attendance?.academicDay ?? 0)}
              </div>
            </div>
            <div className="ems-mks-att-row">
              <div className="ems-mks-att-lbl ems-mks-att-present">
                {L.present}
              </div>
              <div className="ems-mks-att-val ems-mks-att-present">
                {num(r.attendance?.present ?? 0)}
              </div>
            </div>
            <div className="ems-mks-att-row">
              <div className="ems-mks-att-lbl ems-mks-att-absent">
                {L.absent}
              </div>
              <div className="ems-mks-att-val ems-mks-att-absent">
                {num(r.attendance?.absent ?? 0)}
              </div>
            </div>
          </>
        )}

        {/* Progress */}
        {visibleFields.progress && (
          <div className="ems-mks-progress">
            <div className="lbl">{L.progress}</div>
            <div className="opts">
              <input type="checkbox" readOnly /> {L.good}
              <input type="checkbox" readOnly /> {L.needImprovement}
              <input type="checkbox" readOnly /> {L.bad}
            </div>
          </div>
        )}

        {/* Authorization */}
        <table className="ems-mks-auth">
          <thead>
            <tr>
              <th className="lbl"></th>
              <th>{L.signTeacher}</th>
              <th>{L.signGuardian}</th>
              <th>{L.signPrincipal}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td className="lbl">{L.authorization}</td>
              <td>
                {teacherSig && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={teacherSig}
                    alt={teacherName ?? "Teacher"}
                    className="ems-sig-img"
                    draggable={false}
                  />
                )}
              </td>
              <td></td>
              <td>
                {principalSig && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={principalSig}
                    alt={principalName ?? "Principal"}
                    className="ems-sig-img"
                    draggable={false}
                  />
                )}
              </td>
            </tr>
          </tbody>
        </table>

        {r.activities && r.activities.length > 0 && (
          <p className="mb-0 mt-2 ems-fs-12 text-muted">
            <b className="text-dark">{L.activities}:</b> {r.activities.join(" · ")}
          </p>
        )}
      </div>

      <div className="ems-sheet-footer">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src="/assets/images/increlog-logo.png" alt="Increlog" width={16} height={16} draggable={false} style={{ height: 16, width: "auto", verticalAlign: -3 }} />
        <span>{L.developedBy}</span>
      </div>
    </div>
  );
}
