/* global React, Icon, fmtMoney, initials, productById, formatDate, StatusBadge, CartSummary, SidePanel */
const { useState: uS3 } = React;

// ===== Checkout / Payment =====
function Checkout({ payload, setRoute }) {
  const { cart, patient, total, subtotal, shipping, onSubmit } = payload;
  const [tab, setTab] = uS3("card");
  const [card, setCard] = uS3({ number: "", exp: "", cvc: "", postcode: "" });
  const [name, setName] = uS3("Beaumont Aesthetics Ltd");
  const [processing, setProcessing] = uS3(false);

  const formatCard = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(\d{4})(?=\d)/g, "$1 ");
  const formatExp = (v) => {
    const d = v.replace(/\D/g, "").slice(0, 4);
    return d.length > 2 ? d.slice(0, 2) + " / " + d.slice(2) : d;
  };

  const submit = (e) => {
    e.preventDefault();
    setProcessing(true);
    setTimeout(() => {
      onSubmit();
      setProcessing(false);
    }, 1400);
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Step 3 of 3</div>
          <h1 className="page-title">Review & pay</h1>
          <p className="page-sub">Charging the clinic's saved card. Patient is not charged. We'll email a VAT receipt and dispatch confirmation.</p>
        </div>
      </div>

      <div className="stepper">
        <div className="step done"><div className="step-num"><Icon.Check /></div>Patient</div>
        <div className="step-divider" />
        <div className="step done"><div className="step-num"><Icon.Check /></div>Treatment</div>
        <div className="step-divider" />
        <div className="step active"><div className="step-num">3</div>Review & pay</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card">
            <div className="section-h"><h2>Patient</h2><button className="btn btn-link" onClick={() => setRoute("new")}>Edit</button></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, fontSize: 13 }}>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>Name</div>
                <div style={{ fontWeight: 500 }}>{patient.first} {patient.last}</div>
                <div className="muted" style={{ marginTop: 2 }}>{patient.dob ? formatDate(patient.dob) : ""}</div>
              </div>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>Delivery</div>
                <div>{patient.address || "—"}</div>
                <div className="muted">{patient.postcode || ""}</div>
              </div>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>Clinical</div>
                <div>BMI <strong className="tnum">{typeof patient.bmi === "number" ? patient.bmi.toFixed(1) : patient.bmi || "—"}</strong></div>
                <div className="muted">{patient.weight}kg · {patient.height}cm</div>
              </div>
              <div>
                <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 4 }}>GP</div>
                <div>{patient.gp || (patient.gpName ? patient.gpName + " · " + patient.gpSurgery : "—")}</div>
              </div>
            </div>
          </div>

          <form className="pay-card" onSubmit={submit}>
            <div className="pay-tabs">
              <button type="button" className={"pay-tab" + (tab === "card" ? " active" : "")} onClick={() => setTab("card")}>Card</button>
              <button type="button" className={"pay-tab" + (tab === "saved" ? " active" : "")} onClick={() => setTab("saved")}>Saved methods</button>
            </div>

            <div className="pay-body">
              {tab === "card" && (
                <>
                  <div className="field" style={{ marginBottom: 14 }}>
                    <label>Cardholder name</label>
                    <input className="input" value={name} onChange={(e) => setName(e.target.value)} />
                  </div>
                  <div className="field" style={{ marginBottom: 14 }}>
                    <label>Card information</label>
                    <div className="card-input">
                      <div className="card-input-row">
                        <input placeholder="1234 1234 1234 1234" value={card.number} onChange={(e) => setCard({ ...card, number: formatCard(e.target.value) })} />
                        <div className="card-brands">
                          <div className="card-brand" style={{ background: "#1A1F71" }}>VISA</div>
                          <div className="card-brand" style={{ background: "#EB001B" }}>MC</div>
                          <div className="card-brand" style={{ background: "#006FCF" }}>AMEX</div>
                        </div>
                      </div>
                      <div className="card-input-grid">
                        <div><input placeholder="MM / YY" value={card.exp} onChange={(e) => setCard({ ...card, exp: formatExp(e.target.value) })} /></div>
                        <div><input placeholder="CVC" maxLength="4" value={card.cvc} onChange={(e) => setCard({ ...card, cvc: e.target.value.replace(/\D/g, "") })} /></div>
                      </div>
                    </div>
                  </div>
                  <div className="field" style={{ marginBottom: 6 }}>
                    <label>Billing postcode</label>
                    <input className="input" placeholder="M1 5AB" value={card.postcode} onChange={(e) => setCard({ ...card, postcode: e.target.value.toUpperCase() })} />
                  </div>
                  <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-3)", marginTop: 14 }}>
                    <input type="checkbox" defaultChecked /> Save this card to Beaumont Aesthetics
                  </label>
                </>
              )}
              {tab === "saved" && (
                <>
                  <div style={{ border: "1px solid var(--accent)", boxShadow: "0 0 0 1px var(--accent)", borderRadius: 10, padding: 16, display: "flex", alignItems: "center", gap: 14, background: "var(--accent-soft)" }}>
                    <div style={{ width: 38, height: 24, borderRadius: 4, background: "#1A1F71", color: "#fff", display: "grid", placeItems: "center", fontSize: 9, fontWeight: 700 }}>VISA</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 500, fontSize: 13 }}>Visa ending 4242</div>
                      <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Beaumont Aesthetics Ltd · Expires 09/29</div>
                    </div>
                    <Icon.Check style={{ color: "var(--accent)" }} />
                  </div>
                  <button type="button" className="btn btn-ghost" style={{ marginTop: 12, width: "100%", justifyContent: "center" }}>+ Add new card</button>
                </>
              )}
            </div>
          </form>

          <div style={{ display: "flex", gap: 12, padding: 16, background: "var(--canvas-2)", border: "1px solid var(--line)", borderRadius: 12, fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55 }}>
            <Icon.Lock style={{ flexShrink: 0, marginTop: 2, color: "var(--ink-2)" }} />
            <div>
              Charges are processed by Stripe. Card details never touch our servers. By submitting, you sign off this prescription as the responsible prescriber and confirm the patient has been clinically assessed.
            </div>
          </div>
        </div>

        <div style={{ position: "sticky", top: 88, alignSelf: "start" }}>
          <SidePanel title="Order">
            <CartSummary cart={cart} subtotal={subtotal} shipping={shipping} total={total} />
            <button className="btn btn-accent btn-lg" onClick={submit} disabled={processing} style={{ width: "100%", justifyContent: "center", marginTop: 14 }}>
              {processing ? "Processing…" : <><Icon.Lock /> Pay {fmtMoney(total)}</>}
            </button>
            <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", marginTop: 8 }} onClick={() => setRoute("new")}>← Back</button>
          </SidePanel>
        </div>
      </div>
    </div>
  );
}

// ===== Confirmation =====
function OrderConfirmation({ orderId, orders, patients, setRoute }) {
  const order = orders.find(o => o.id === orderId);
  const patient = patients.find(p => p.id === order.patientId);
  return (
    <div className="page" style={{ maxWidth: 720, marginInline: "auto" }}>
      <div style={{ textAlign: "center", padding: "40px 0 32px" }}>
        <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", margin: "0 auto 20px" }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
        </div>
        <div className="page-eyebrow">Order placed</div>
        <h1 className="page-title">Prescription submitted.</h1>
        <p className="page-sub" style={{ margin: "10px auto 0" }}>
          We've sent <strong>{patient.first}</strong> a delivery confirmation. Dispensing usually starts within 2 working hours.
        </p>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em" }}>Order</div>
            <div className="serif tnum" style={{ fontSize: 22, letterSpacing: "-0.02em" }}>{order.id}</div>
          </div>
          <StatusBadge status={order.status} />
        </div>
        <div style={{ padding: "16px 24px" }}>
          {order.items.map(it => {
            const p = productById(it.pid);
            return (
              <div key={it.pid} className="order-line">
                <div className="order-line-img">{p.img ? <img src={p.img} alt={p.strength} /> : <div style={{ fontSize: 9 }}>{p.strength}</div>}</div>
                <div className="order-line-body">
                  <div className="order-line-title">{p.name}</div>
                  <div className="order-line-sub">{p.strength} · 4 doses · qty {it.qty}</div>
                </div>
                <div className="order-line-price tnum">{fmtMoney(p.price * it.qty)}</div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: "16px 24px", borderTop: "1px solid var(--line)" }}>
          <div className="summary-line total"><span>Total charged</span><span className="v tnum">{fmtMoney(order.total)}</span></div>
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, marginTop: 24, justifyContent: "center" }}>
        <button className="btn btn-ghost" onClick={() => setRoute("orders")}>View all orders</button>
        <button className="btn btn-primary" onClick={() => setRoute("dashboard")}>Back to dashboard</button>
      </div>
    </div>
  );
}

// ===== Order history =====
function OrderHistory({ orders, patients, setRoute }) {
  const [filter, setFilter] = uS3("all");
  const filtered = filter === "all" ? orders : orders.filter(o => o.status === filter);
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Order log</div>
          <h1 className="page-title">Orders</h1>
          <p className="page-sub">{orders.length} orders · {orders.filter(o => o.status === "shipped").length} shipped this month</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost">Download invoice CSV</button>
        </div>
      </div>

      <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 8, width: "fit-content", marginBottom: 16 }}>
        {[["all","All"],["paid","Paid"],["shipped","Shipped"],["review","Review"],["cancelled","Cancelled"]].map(([k, l]) => (
          <button key={k} className="btn btn-sm" style={{
            background: filter === k ? "var(--ink)" : "transparent",
            color: filter === k ? "#fff" : "var(--ink-3)",
            border: "none",
          }} onClick={() => setFilter(k)}>{l}</button>
        ))}
      </div>

      <div className="tbl-card">
        <table className="tbl">
          <thead>
            <tr><th>Order</th><th>Date</th><th>Patient</th><th>Items</th><th>Total</th><th>Status</th><th>Tracking</th></tr>
          </thead>
          <tbody>
            {filtered.map(o => {
              const p = patients.find(p => p.id === o.patientId);
              return (
                <tr key={o.id}>
                  <td className="tnum"><strong>{o.id}</strong></td>
                  <td>{formatDate(o.date)}</td>
                  <td>
                    <div className="patient-cell">
                      <div className="patient-avatar">{initials(p.first, p.last)}</div>
                      <div className="patient-name">{p.first} {p.last}</div>
                    </div>
                  </td>
                  <td>{o.items.map(it => productById(it.pid).strength + (it.qty > 1 ? " ×" + it.qty : "")).join(", ")}</td>
                  <td className="tnum"><strong>{fmtMoney(o.total)}</strong></td>
                  <td><StatusBadge status={o.status} /></td>
                  <td className="tnum muted" style={{ fontSize: 12 }}>{o.tracking || "—"}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ===== Settings =====
function Settings() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Account</div>
          <h1 className="page-title">Clinic settings</h1>
          <p className="page-sub">Manage your prescriber profile, billing details and team access.</p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 24 }}>
        <nav style={{ display: "flex", flexDirection: "column", gap: 2, fontSize: 13 }}>
          {["Clinic profile","Prescriber details","Billing & invoices","Saved cards","Team","API & integrations","Audit log"].map((s, i) => (
            <button key={s} className="btn btn-ghost" style={{ justifyContent: "flex-start", border: "none", background: i === 0 ? "var(--canvas-2)" : "transparent", fontWeight: i === 0 ? 600 : 400 }}>{s}</button>
          ))}
        </nav>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card">
            <h3 className="serif" style={{ fontSize: 20, fontWeight: 400, margin: "0 0 4px", letterSpacing: "-0.02em" }}>Clinic profile</h3>
            <div className="muted" style={{ fontSize: 12, marginBottom: 18 }}>This is shown on dispatch labels and patient communications.</div>
            <div className="field-row">
              <div className="field"><label>Clinic name</label><input className="input" defaultValue="Beaumont Aesthetics" /></div>
              <div className="field"><label>Trading as</label><input className="input" defaultValue="Beaumont Aesthetics Ltd" /></div>
            </div>
            <div className="field-row" style={{ marginTop: 14 }}>
              <div className="field"><label>Companies House no.</label><input className="input tnum" defaultValue="11892043" /></div>
              <div className="field"><label>VAT number</label><input className="input tnum" defaultValue="GB 318 4209 17" /></div>
            </div>
            <div className="field-row" style={{ marginTop: 14, gridTemplateColumns: "2fr 1fr" }}>
              <div className="field"><label>Registered address</label><input className="input" defaultValue="14 Beaumont Road, Manchester" /></div>
              <div className="field"><label>Postcode</label><input className="input" defaultValue="M14 5GP" /></div>
            </div>
          </div>

          <div className="card">
            <h3 className="serif" style={{ fontSize: 20, fontWeight: 400, margin: "0 0 4px", letterSpacing: "-0.02em" }}>Prescriber on file</h3>
            <div className="muted" style={{ fontSize: 12, marginBottom: 18 }}>The named clinician who signs off prescriptions submitted from this account.</div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, padding: 16, background: "var(--canvas-2)", borderRadius: 10 }}>
              <div className="patient-avatar" style={{ width: 44, height: 44, fontSize: 14 }}>JS</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>Dr. John Smith</div>
                <div className="muted" style={{ fontSize: 12 }}>Independent prescriber · GPhC 2087443 · Verified Mar 2026</div>
              </div>
              <button className="btn btn-ghost btn-sm">Manage</button>
            </div>
          </div>

          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
            <button className="btn btn-ghost">Cancel</button>
            <button className="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Checkout = Checkout;
window.OrderConfirmation = OrderConfirmation;
window.OrderHistory = OrderHistory;
window.Settings = Settings;
