/* global React, Icon, fmtMoney, initials, productById, formatDate */
const { useState: uS6 } = React;

// Pharmalyfe-style prescriber declarations.
// 6 declarations + product-specific (weight-loss) acknowledgements.
// All must be checked before continuing to payment.
const GENERAL_DECLARATIONS = [
  {
    id: "responsibility",
    title: "Clinical responsibility",
    body: "I am the prescribing clinician for the patient(s) in this order. I have personally undertaken (or directly supervised) a clinical assessment and accept clinical responsibility for the appropriateness, safety and legality of every prescription generated by this checkout."
  },
  {
    id: "registration",
    title: "Registration & indemnity",
    body: "I am a registered prescriber in good standing with my professional regulator (GMC, NMC, GPhC or GDC), my registration is unrestricted in respect of independent prescribing, and I hold valid professional indemnity insurance covering this scope of practice."
  },
  {
    id: "off-label",
    title: "Licensed indication",
    body: "I confirm I am prescribing within the licensed indication for each medicine, or — where prescribing off-label — I have a documented clinical rationale, the patient has been informed, and the decision is recorded in their notes."
  },
  {
    id: "records",
    title: "Patient records",
    body: "Up-to-date clinical records exist for each patient, including identity verification, medical and medication history, contraindications check, and a documented consultation supporting today's prescription. I will retain these records for the period required by law."
  },
  {
    id: "supply",
    title: "Supply & dispensing",
    body: "I authorise Pharmalyfe's contracted dispensing pharmacist to dispense and dispatch the prescribed medicines to the patient address(es) supplied. I understand the prescription will only be released to the pharmacist after my e-signature is verified."
  },
  {
    id: "data",
    title: "Data protection",
    body: "I confirm I have a lawful basis to share patient personal and clinical data with Pharmalyfe and the dispensing pharmacist for the purpose of prescription fulfilment, in accordance with UK GDPR and my professional confidentiality duties."
  }
];

const WEIGHT_LOSS_DECLARATIONS = [
  {
    id: "bmi",
    title: "BMI threshold",
    body: "Each patient meets the licensed BMI threshold for GLP-1 weight management: BMI ≥ 30, or BMI 27–30 with at least one documented weight-related comorbidity (T2DM, hypertension, dyslipidaemia, OSA or established CVD)."
  },
  {
    id: "contraindications",
    title: "Contraindications screened",
    body: "I have screened each patient for contraindications including personal/family history of medullary thyroid carcinoma or MEN2, pregnancy or breastfeeding, severe gastrointestinal disease, pancreatitis, and known hypersensitivity to the active substance."
  },
  {
    id: "monitoring",
    title: "Monitoring & follow-up",
    body: "I have a documented plan in place for monitoring weight, side-effects and tolerability at appropriate intervals, with arrangements for dose escalation, de-escalation or discontinuation as clinically indicated."
  },
  {
    id: "counselling",
    title: "Patient counselling",
    body: "Each patient has been counselled on injection technique, dose schedule, common side-effects, red-flag symptoms requiring urgent review, and the role of diet and physical activity alongside pharmacotherapy."
  }
];

function DeclareScreen({ allocations, patients, setRoute, declarations, setDeclarations }) {
  const all = [...GENERAL_DECLARATIONS, ...WEIGHT_LOSS_DECLARATIONS];
  const allChecked = all.every(d => declarations[d.id]);
  const checkedCount = all.filter(d => declarations[d.id]).length;

  const toggle = (id) => setDeclarations({ ...declarations, [id]: !declarations[id] });
  const checkAll = () => {
    const next = {};
    all.forEach(d => next[d.id] = true);
    setDeclarations(next);
  };

  return (
    <div className="page" style={{ maxWidth: 980, marginInline: "auto" }}>
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Step 3 of 5 · Prescriber declarations</div>
          <h1 className="page-title">Confirm before checkout</h1>
          <p className="page-sub">Read each statement carefully. By checking the boxes you take legal and clinical responsibility for the prescriptions about to be created.</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost" onClick={() => setRoute("allocate")}>← Back</button>
        </div>
      </div>

      <div className="stepper">
        <div className="step done"><div className="step-num"><Icon.Check /></div>Basket</div>
        <div className="step-divider" />
        <div className="step done"><div className="step-num"><Icon.Check /></div>Allocate</div>
        <div className="step-divider" />
        <div className="step active"><div className="step-num">3</div>Declare</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">4</div>Pay</div>
        <div className="step-divider" />
        <div className="step"><div className="step-num">5</div>Sign</div>
      </div>

      {/* Patient summary strip */}
      <div className="card" style={{ padding: "14px 18px", marginBottom: 16, display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--ink-4)" }}>Declaring for</div>
        {allocations.map((a, i) => {
          const p = patients.find(pp => pp.id === a.patientId);
          return (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 10px 6px 6px", background: "var(--canvas-2)", borderRadius: 999 }}>
              <div className="patient-avatar" style={{ width: 26, height: 26, fontSize: 10 }}>{initials(p.first, p.last)}</div>
              <div style={{ fontSize: 12 }}>
                <span style={{ fontWeight: 500 }}>{p.first} {p.last}</span>
                <span style={{ color: "var(--ink-4)", marginLeft: 6 }} className="tnum">BMI {typeof p.bmi === "number" ? p.bmi.toFixed(1) : p.bmi}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <DeclarationGroup
            title="General prescriber declarations"
            subtitle="Apply to every prescription you generate via Pharmalyfe."
            items={GENERAL_DECLARATIONS}
            checked={declarations}
            onToggle={toggle}
          />
          <DeclarationGroup
            title="Weight-management specific"
            subtitle="Required for tirzepatide and semaglutide prescriptions."
            items={WEIGHT_LOSS_DECLARATIONS}
            checked={declarations}
            onToggle={toggle}
          />
        </div>

        <div style={{ position: "sticky", top: 88, alignSelf: "start" }}>
          <div className="card">
            <div className="section-h" style={{ marginBottom: 8 }}><h2>Progress</h2></div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 12 }}>
              <span className="serif tnum" style={{ fontSize: 36, letterSpacing: "-0.03em" }}>{checkedCount}</span>
              <span style={{ color: "var(--ink-4)" }}>of {all.length} confirmed</span>
            </div>
            <div style={{ height: 6, background: "var(--canvas-2)", borderRadius: 999, overflow: "hidden", marginBottom: 16 }}>
              <div style={{ height: "100%", width: `${(checkedCount / all.length) * 100}%`, background: "var(--accent)", transition: "width 200ms" }} />
            </div>

            <button className="btn btn-ghost btn-sm" onClick={checkAll} style={{ width: "100%", justifyContent: "center", marginBottom: 8 }}>Check all (skim mode)</button>
            <div style={{ fontSize: 11, color: "var(--ink-4)", textAlign: "center", marginBottom: 14 }}>
              You're attesting under your professional registration. Read each carefully.
            </div>

            <div className="divider" style={{ margin: "8px 0 14px" }} />

            <button className="btn btn-accent btn-lg" disabled={!allChecked} onClick={() => setRoute("pay")} style={{ width: "100%", justifyContent: "center" }}>
              {allChecked ? <>Continue to payment <Icon.ChevronR /></> : `${all.length - checkedCount} declaration${(all.length - checkedCount) !== 1 ? "s" : ""} remaining`}
            </button>
          </div>

          <div style={{ marginTop: 12, padding: 14, fontSize: 11, color: "var(--ink-3)", lineHeight: 1.55 }}>
            <strong style={{ display: "block", marginBottom: 4, color: "var(--ink-2)" }}>What happens next?</strong>
            We capture your declarations against your prescriber profile, take payment, then queue each prescription for your e-signature. Nothing is dispensed until you sign.
          </div>
        </div>
      </div>
    </div>
  );
}

function DeclarationGroup({ title, subtitle, items, checked, onToggle }) {
  return (
    <div className="card" style={{ padding: 0 }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
        <div style={{ fontFamily: "'Newsreader', serif", fontSize: 20, letterSpacing: "-0.01em" }}>{title}</div>
        <div style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 2 }}>{subtitle}</div>
      </div>
      <div>
        {items.map((d, i) => (
          <label key={d.id} style={{
            display: "grid",
            gridTemplateColumns: "auto 1fr",
            gap: 14,
            padding: "16px 20px",
            borderTop: i > 0 ? "1px solid var(--line)" : "none",
            cursor: "pointer",
            background: checked[d.id] ? "var(--accent-soft)" : "transparent",
            transition: "background 120ms"
          }}>
            <div style={{ paddingTop: 1 }}>
              <input type="checkbox" checked={!!checked[d.id]} onChange={() => onToggle(d.id)} style={{ width: 18, height: 18, cursor: "pointer", accentColor: "var(--accent)" }} />
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4, color: "var(--ink)" }}>{d.title}</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.55 }}>{d.body}</div>
            </div>
          </label>
        ))}
      </div>
    </div>
  );
}

window.DeclareScreen = DeclareScreen;
window.GENERAL_DECLARATIONS = GENERAL_DECLARATIONS;
window.WEIGHT_LOSS_DECLARATIONS = WEIGHT_LOSS_DECLARATIONS;
