import type { Procedure, ProcedureOption } from "@/data/consentiq/procedures";

export type PatientDetails = {
  fullName: string;
  dob: string;
  mrn: string;
  languagePref: string;
};

export type BuilderValues = Record<string, string>;

const serif = {
  fontFamily: 'Georgia, "Times New Roman", serif',
};

function labelForOption(opt: ProcedureOption, value: string | undefined): string {
  if (!value) return "—";
  if (opt.kind === "text") return value;
  const choice = opt.choices?.find((c) => c.value === value);
  return choice?.label ?? value;
}

function SectionHeading({
  num,
  children,
}: {
  num: number;
  children: React.ReactNode;
}) {
  return (
    <h2
      style={serif}
      className="mt-8 border-b border-black/30 pb-1 text-[18px] font-bold text-black"
    >
      {num}. {children}
    </h2>
  );
}

export function ConsentDocument({
  procedure,
  patient,
  values,
}: {
  procedure: Procedure;
  patient: PatientDetails;
  values: BuilderValues;
}) {
  const anaesthesiaLabel =
    procedure.options.find((o) => o.id === "anaesthesia") &&
    labelForOption(
      procedure.options.find((o) => o.id === "anaesthesia")!,
      values.anaesthesia,
    );

  const lateralityLabel =
    procedure.options.find((o) => o.id === "laterality") &&
    labelForOption(
      procedure.options.find((o) => o.id === "laterality")!,
      values.laterality,
    );

  const otherOptions = procedure.options.filter(
    (o) => o.id !== "anaesthesia" && o.id !== "laterality",
  );

  const common = procedure.risks.filter((r) => !r.severity || r.severity === "common");
  const serious = procedure.risks.filter((r) => r.severity === "serious");
  const rare = procedure.risks.filter((r) => r.severity === "rare");

  return (
    <div
      className="consentiq-document relative mx-auto max-w-[820px] rounded-lg border border-[var(--color-line)] bg-white p-10 shadow-sm print:border-0 print:p-0 print:shadow-none"
      style={{
        ...serif,
        fontSize: "18px",
        lineHeight: "1.55",
        color: "#0f172a",
      }}
    >
      {/* Draft watermark */}
      <div
        aria-hidden
        className="pointer-events-none absolute inset-0 flex items-center justify-center select-none"
        style={{
          transform: "rotate(-22deg)",
          fontSize: "120px",
          fontWeight: 900,
          color: "rgba(234, 88, 12, 0.08)",
          letterSpacing: "0.08em",
          ...serif,
        }}
      >
        DRAFT
      </div>

      <div className="relative">
        {/* Letterhead */}
        <header className="border-b-2 border-black pb-4">
          <div
            className="text-[11px] font-bold uppercase tracking-[0.18em] text-black"
            style={{ fontFamily: "Inter, sans-serif" }}
          >
            OrthoGlobe Partner Hospital
          </div>
          <div
            className="mt-1 text-[11px] text-black/60"
            style={{ fontFamily: "Inter, sans-serif" }}
          >
            Consent for surgical treatment · ConsentIQ draft output
          </div>
          <h1
            style={serif}
            className="mt-4 text-[26px] font-bold leading-tight text-black"
          >
            Consent to {procedure.name}
          </h1>
        </header>

        {/* Patient block */}
        <section className="mt-6 grid grid-cols-2 gap-x-8 gap-y-2 border-b border-black/20 pb-4 text-[15px]">
          <div>
            <span className="font-bold">Patient name: </span>
            {patient.fullName || "—"}
          </div>
          <div>
            <span className="font-bold">Date of birth: </span>
            {patient.dob || "—"}
          </div>
          <div>
            <span className="font-bold">MRN: </span>
            {patient.mrn || "—"}
          </div>
          <div>
            <span className="font-bold">Language preference: </span>
            {patient.languagePref || "English"}
          </div>
        </section>

        {/* Procedure block */}
        <section className="mt-4 grid grid-cols-2 gap-x-8 gap-y-2 border-b border-black/20 pb-4 text-[15px]">
          <div>
            <span className="font-bold">Procedure: </span>
            {procedure.name}
          </div>
          <div>
            <span className="font-bold">Side: </span>
            {lateralityLabel ?? "—"}
          </div>
          <div>
            <span className="font-bold">Anaesthesia: </span>
            {anaesthesiaLabel ?? procedure.anaesthesia.join(", ")}
          </div>
          <div>
            <span className="font-bold">Approx. duration: </span>~
            {procedure.approxDurationMin} min
          </div>
          {otherOptions.map((o) => (
            <div key={o.id}>
              <span className="font-bold">{o.label}: </span>
              {labelForOption(o, values[o.id])}
            </div>
          ))}
        </section>

        <SectionHeading num={1}>What the procedure involves</SectionHeading>
        <p className="mt-2">{procedure.summary}</p>
        <ul className="mt-3 list-disc space-y-1 pl-6">
          {procedure.involves.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>

        <SectionHeading num={2}>Benefits</SectionHeading>
        <ul className="mt-2 list-disc space-y-1 pl-6">
          {procedure.benefits.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>

        <SectionHeading num={3}>Risks</SectionHeading>
        {common.length > 0 && (
          <>
            <p className="mt-2 font-bold">Common</p>
            <ul className="mt-1 list-disc space-y-1 pl-6">
              {common.map((r) => (
                <li key={r.title}>
                  <span className="font-bold">{r.title}. </span>
                  {r.detail}
                </li>
              ))}
            </ul>
          </>
        )}
        {rare.length > 0 && (
          <>
            <p className="mt-3 font-bold">Rare</p>
            <ul className="mt-1 list-disc space-y-1 pl-6">
              {rare.map((r) => (
                <li key={r.title}>
                  <span className="font-bold">{r.title}. </span>
                  {r.detail}
                </li>
              ))}
            </ul>
          </>
        )}
        {serious.length > 0 && (
          <>
            <p className="mt-3 font-bold">Serious</p>
            <ul className="mt-1 list-disc space-y-1 pl-6">
              {serious.map((r) => (
                <li key={r.title}>
                  <span className="font-bold">{r.title}. </span>
                  {r.detail}
                </li>
              ))}
            </ul>
          </>
        )}

        <SectionHeading num={4}>Alternatives</SectionHeading>
        <ul className="mt-2 list-disc space-y-1 pl-6">
          {procedure.alternatives.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>

        <SectionHeading num={5}>Recovery</SectionHeading>
        <ul className="mt-2 list-disc space-y-1 pl-6">
          {procedure.recovery.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>

        <SectionHeading num={6}>Warning signs</SectionHeading>
        <p className="mt-2">
          Contact the ward or your treating team urgently if you experience any
          of the following:
        </p>
        <ul className="mt-2 list-disc space-y-1 pl-6">
          {procedure.warnings.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>

        <SectionHeading num={7}>Consent statement</SectionHeading>
        <p className="mt-2">
          I confirm that I have read and understood the information above. I
          have had the opportunity to ask questions about the procedure,
          including its benefits, risks, and alternatives. I understand that
          additional procedures may be required if unexpected findings arise
          during surgery. I consent to {procedure.name.toLowerCase()} being
          performed by the named surgeon or a deputy under their supervision.
        </p>

        {/* Signature block */}
        <section className="mt-10 grid grid-cols-2 gap-x-10 gap-y-8">
          {[
            { label: "Patient signature" },
            { label: "Date" },
            { label: "Witness signature" },
            { label: "Date" },
            { label: "Surgeon signature" },
            { label: "Date" },
          ].map((s, i) => (
            <div key={`${s.label}-${i}`}>
              <div className="border-b border-black pb-6" />
              <div
                className="mt-1 text-[11px] font-semibold uppercase tracking-wider text-black/60"
                style={{ fontFamily: "Inter, sans-serif" }}
              >
                {s.label}
              </div>
            </div>
          ))}
        </section>

        <footer
          className="mt-10 border-t border-black/20 pt-3 text-[11px] text-black/50"
          style={{ fontFamily: "Inter, sans-serif" }}
        >
          Generated by ConsentIQ · OrthoGlobe. DRAFT output — requires
          clinician review and signature before clinical use.
        </footer>
      </div>
    </div>
  );
}
