/* =============================================================
   CoreIQ Office — Customers / patients (this pharmacy)
   Real, tenant-scoped customer directory served by /customers.
   Searchable list → click a row for the full 360 profile:
   contact + clinical (NDSS/HENS) detail, the linked A/R account
   balance, lifetime spend, and recent purchase history. No mock data.
   ============================================================= */
const { useState: cuUseState, useEffect: cuUseEffect, useRef: cuUseRef } = React;

function CustomersScreen() {
  const [q, setQ] = cuUseState("");
  const [data, setData] = cuUseState({ total: 0, customers: [] });
  const [loading, setLoading] = cuUseState(true);
  const [err, setErr] = cuUseState(null);
  const [sort, setSort] = cuUseState({ col: "name", dir: "asc" });
  const [selId, setSelId] = cuUseState(null);
  const [detail, setDetail] = cuUseState(null);
  const [detailLoading, setDetailLoading] = cuUseState(false);
  const seq = cuUseRef(0);

  // Debounced live search (empty query = alphabetical browse).
  cuUseEffect(() => {
    const s = ++seq.current;
    setLoading(true);
    const t = setTimeout(() => {
      window.OfficeAPI.listCustomers(q.trim(), 60, sort.col, sort.dir)
        .then((d) => { if (s !== seq.current) return; setData(d); setErr(null); setLoading(false); })
        .catch((e) => { if (s !== seq.current) return; setErr(String(e.message || e)); setLoading(false); });
    }, 220);
    return () => clearTimeout(t);
  }, [q, sort.col, sort.dir]);

  const open = (id) => {
    setSelId(id); setDetail(null); setDetailLoading(true);
    window.OfficeAPI.getCustomer(id)
      .then((d) => { setDetail(d); setDetailLoading(false); })
      .catch((e) => { setErr(String(e.message || e)); setDetailLoading(false); });
  };

  const money = (c) => (c == null ? "—" : window.officeMoney(c / 100));
  const day = (s) => (s ? String(s).slice(0, 10) : "—");

  const COLS = [
    { label: "Customer", key: "name" },
    { label: "Code", key: "code" },
    { label: "Contact", key: "contact" },
    { label: "Suburb", key: "suburb" },
    { label: "Account", key: "balance", num: true },
  ];
  // Click a header to sort server-side (whole dataset, not just the page).
  // Same column toggles direction; balance defaults to descending (biggest first).
  const toggleSort = (key) =>
    setSort((s) => (s.col === key
      ? { col: key, dir: s.dir === "asc" ? "desc" : "asc" }
      : { col: key, dir: key === "balance" ? "desc" : "asc" }));
  const arrow = (key) => (sort.col === key ? (sort.dir === "asc" ? " ↑" : " ↓") : "");

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Customers · this pharmacy</span>
          <h2 className="off-screen-title">Customers</h2>
        </div>
        <div className="off-screen-actions">
          <span className="off-filter-count">{data.total.toLocaleString()} patient / account records</span>
        </div>
      </header>

      <div className="off-screen-body" style={{ display: "flex", gap: 16, overflow: "hidden" }}>
        {/* ---- list (scrolls independently of the detail panel) ---- */}
        <div style={{ flex: 1, minWidth: 0, overflowY: "auto", paddingRight: 4 }}>
          <div className="off-filters" style={{ alignItems: "center" }}>
            <div className="off-topbar-search" style={{ maxWidth: 460, flex: "0 1 460px" }}>
              <OIcon name="search" className="off-topbar-search-ic" />
              <input
                className="input"
                placeholder="Search by name, phone, email or code…"
                value={q}
                onChange={(e) => setQ(e.target.value)}
                autoFocus
              />
            </div>
            <span className="off-filter-count">{loading ? "Searching…" : `${data.customers.length} shown`}</span>
          </div>

          {err && <div className="signin-error" style={{ marginBottom: 12 }}>Couldn’t reach the customers API — {err}</div>}

          <div className="off-table" style={{ minWidth: 0 }}>
            <div className="off-grid" style={{ gridTemplateColumns: "1.7fr 120px 1.3fr 0.9fr 110px" }}>
              {COLS.map((col) => (
                <div
                  key={col.key}
                  className="off-grid-headcell"
                  onClick={() => toggleSort(col.key)}
                  title="Sort"
                  style={Object.assign({ cursor: "pointer", userSelect: "none" }, col.num ? { justifyContent: "flex-end" } : {})}
                >
                  {col.label}{arrow(col.key)}
                </div>
              ))}
              {data.customers.map((c) => (
                <div
                  className="off-grid-row"
                  key={c.id}
                  onClick={() => open(c.id)}
                  style={{ cursor: "pointer", background: c.id === selId ? "var(--surface-2, rgba(0,0,0,0.04))" : undefined }}
                >
                  <div className="off-grid-cell off-cell-strong">
                    {c.name}{c.hasNdss ? <span className="off-badge" style={{ marginLeft: 6 }}>NDSS</span> : null}
                  </div>
                  <div className="off-grid-cell off-cell-mono off-muted">{c.code || "—"}</div>
                  <div className="off-grid-cell off-muted">{c.phone || c.email || "—"}</div>
                  <div className="off-grid-cell off-muted">{c.locality || "—"}</div>
                  <div className="off-grid-cell off-cell-num">{c.accountBalanceCents == null ? "—" : money(c.accountBalanceCents)}</div>
                </div>
              ))}
            </div>
          </div>

          {!loading && data.customers.length === 0 && !err && (
            <div className="off-empty">
              <div className="empty-icon"><OIcon name="search" width={20} height={20} /></div>
              <div className="empty-title">No customers match “{q}”.</div>
            </div>
          )}
        </div>

        {/* ---- 360 detail ---- */}
        {selId && (
          <aside className="off-card" style={{ width: 430, flex: "0 0 430px", alignSelf: "stretch", overflowY: "auto" }}>
            {detailLoading && <div className="off-muted" style={{ padding: 8 }}>Loading…</div>}
            {detail && (() => {
              const c = detail.customer;
              const acct = detail.accounts[0];
              const Row = ({ label, value }) => value == null || value === "" ? null : (
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "3px 0", fontSize: "var(--fs-13)" }}>
                  <span className="off-muted">{label}</span>
                  <span style={{ textAlign: "right" }}>{value}</span>
                </div>
              );
              return (
                <div>
                  <div className="off-card-header" style={{ alignItems: "flex-start" }}>
                    <div>
                      <h3 className="off-card-title" style={{ marginBottom: 2 }}>{c.name}</h3>
                      <span className="off-muted" style={{ fontSize: "var(--fs-12)" }}>
                        {c.code ? "#" + c.code : ""}{c.status ? " · " + c.status : ""}
                      </span>
                    </div>
                    <button className="btn btn--ghost btn--sm" onClick={() => { setSelId(null); setDetail(null); }}>Close</button>
                  </div>

                  {/* lifetime + account summary */}
                  <div style={{ display: "flex", gap: 10, margin: "10px 0" }}>
                    <div className="off-card" style={{ flex: 1, padding: 10 }}>
                      <div className="off-muted" style={{ fontSize: "var(--fs-11)", textTransform: "uppercase", letterSpacing: ".05em" }}>Lifetime</div>
                      <div className="off-cell-strong" style={{ fontSize: "var(--fs-16)" }}>{money(detail.lifetime.spendCents)}</div>
                      <div className="off-muted" style={{ fontSize: "var(--fs-12)" }}>{detail.lifetime.orders.toLocaleString()} orders</div>
                    </div>
                    <div className="off-card" style={{ flex: 1, padding: 10 }}>
                      <div className="off-muted" style={{ fontSize: "var(--fs-11)", textTransform: "uppercase", letterSpacing: ".05em" }}>Account</div>
                      <div className="off-cell-strong" style={{ fontSize: "var(--fs-16)" }}>{acct ? money(acct.balanceCents) : "—"}</div>
                      <div className="off-muted" style={{ fontSize: "var(--fs-12)" }}>{acct ? (acct.accountNumber || "charge a/c") : "no account"}</div>
                    </div>
                  </div>

                  {/* contact */}
                  <div style={{ marginTop: 4 }}>
                    <Row label="Phone" value={c.phone || c.mobile} />
                    <Row label="Email" value={c.email} />
                    <Row label="Address" value={[c.addressLine1, c.addressLine2].filter(Boolean).join(", ") || null} />
                    <Row label="Suburb" value={[c.locality, c.region, c.postalCode].filter(Boolean).join(" ") || null} />
                    <Row label="Date of birth" value={c.dateOfBirth ? day(c.dateOfBirth) : null} />
                    <Row label="Gender" value={c.gender} />
                  </div>

                  {/* clinical */}
                  {(c.hasNdss || c.hasHens) && (
                    <div style={{ marginTop: 10, borderTop: "1px solid var(--border, #eee)", paddingTop: 8 }}>
                      <div className="off-muted" style={{ fontSize: "var(--fs-11)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Clinical</div>
                      <Row label="NDSS number" value={c.ndssNumber} />
                      <Row label="NDSS type" value={c.ndssType} />
                      <Row label="NDSS status" value={c.ndssStatus} />
                      <Row label="NDSS expiry" value={c.ndssExpiryDate ? day(c.ndssExpiryDate) : null} />
                      {c.hasHens ? <Row label="HENS" value="registered" /> : null}
                    </div>
                  )}

                  {c.notes && (
                    <div style={{ marginTop: 10, borderTop: "1px solid var(--border, #eee)", paddingTop: 8 }}>
                      <div className="off-muted" style={{ fontSize: "var(--fs-11)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>Notes</div>
                      <div style={{ fontSize: "var(--fs-13)" }}>{c.notes}</div>
                    </div>
                  )}

                  {/* recent purchases */}
                  <div style={{ marginTop: 10, borderTop: "1px solid var(--border, #eee)", paddingTop: 8 }}>
                    <div className="off-muted" style={{ fontSize: "var(--fs-11)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 4 }}>
                      Recent purchases
                    </div>
                    {detail.purchases.length === 0 && <div className="off-muted" style={{ fontSize: "var(--fs-13)" }}>No purchases on file.</div>}
                    {detail.purchases.map((p) => (
                      <div key={p.id} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "3px 0", fontSize: "var(--fs-13)" }}>
                        <span className="off-muted">{day(p.at)}{p.lineCount ? " · " + p.lineCount + " items" : ""}</span>
                        <span className="off-cell-num">{money(p.totalCents)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })()}
          </aside>
        )}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  customers: CustomersScreen,
});
