/* =============================================================
   CoreIQ Office — Store setup (onboarding)
   The front door for a new site: confirm the organisation's trading
   name / legal name / ABN, the site's address + registration numbers
   (PBS approval, AHPRA), seed the built-in RBAC roles, and manage
   operators. Everything writes to the real tenant rows and flows to
   the tills via PowerSync. PINs are never handled here — an
   operator's PIN is established on the till itself.
   ============================================================= */
const { useState: suUseState, useEffect: suUseEffect } = React;

function SetupField({ label, value, onChange, placeholder, required, type }) {
  return (
    <label className="field">
      <span className="field-label">{label}{required ? <span className="field-required"> *</span> : null}</span>
      <input
        className="input"
        type={type || "text"}
        value={value ?? ""}
        placeholder={placeholder || ""}
        onChange={(e) => onChange(e.target.value)}
      />
    </label>
  );
}

function StoreSetupScreen() {
  const [state, setState] = suUseState(null);
  const [err, setErr] = suUseState(null);
  const [busy, setBusy] = suUseState(false);
  const [savedMsg, setSavedMsg] = suUseState(null);

  // Drafts (uncontrolled by server state until Save).
  const [orgDraft, setOrgDraft] = suUseState(null);
  const [siteDraft, setSiteDraft] = suUseState(null);
  const [opDraft, setOpDraft] = suUseState({ firstName: "", lastName: "", email: "", loginCode: "", roleId: "" });

  const load = () =>
    window.OfficeAPI.getOnboarding()
      .then((d) => {
        setState(d);
        setOrgDraft({ ...d.organisation });
        setSiteDraft(d.sites[0] ? { ...d.sites[0] } : null);
        setErr(null);
      })
      .catch((e) => setErr(String(e.message || e)));

  suUseEffect(() => { load(); }, []);

  const flash = (msg) => { setSavedMsg(msg); setTimeout(() => setSavedMsg(null), 2500); };
  const run = (p, done) => {
    setBusy(true);
    p.then((d) => {
      if (d && d.onboarding) {
        setState(d.onboarding);
        setOrgDraft({ ...d.onboarding.organisation });
        setSiteDraft(d.onboarding.sites[0] ? { ...d.onboarding.sites[0] } : null);
      }
      setErr(null); setBusy(false); if (done) done(d);
    }).catch((e) => { setErr(String(e.message || e)); setBusy(false); });
  };

  if (err && !state) return <div className="off-screen"><div className="off-card signin-error">{err}</div></div>;
  if (!state || !orgDraft) return <div className="off-screen"><div className="off-muted" style={{ padding: 24 }}>Loading…</div></div>;

  const pendingName = /pending/i.test(state.organisation.name);
  const rolesReady = state.roles.length > 0;

  const saveOrg = () =>
    run(window.OfficeAPI.patchOrganisation({
      name: orgDraft.name || undefined,
      legalName: orgDraft.legalName || null,
      groupAbn: orgDraft.groupAbn || null,
      timezone: orgDraft.timezone || null,
    }), () => flash("Organisation saved"));

  const saveSite = () =>
    run(window.OfficeAPI.patchSite(siteDraft.id, {
      name: siteDraft.name || undefined,
      pbsApprovalNumber: siteDraft.pbsApprovalNumber || null,
      ahpraPharmacyNumber: siteDraft.ahpraPharmacyNumber || null,
      addressLine1: siteDraft.addressLine1 || null,
      locality: siteDraft.locality || null,
      region: siteDraft.region || null,
      postalCode: siteDraft.postalCode || null,
      phone: siteDraft.phone || null,
      email: siteDraft.email || null,
    }), () => flash("Site saved"));

  const addOperator = () => {
    if (!opDraft.firstName || !opDraft.lastName || !opDraft.roleId) {
      setErr("Operator needs a first name, last name and role");
      return;
    }
    setBusy(true);
    window.OfficeAPI.createOperator({
      firstName: opDraft.firstName,
      lastName: opDraft.lastName,
      email: opDraft.email || null,
      loginCode: opDraft.loginCode || null,
      roleId: opDraft.roleId,
    }).then(() => {
      setOpDraft({ firstName: "", lastName: "", email: "", loginCode: "", roleId: opDraft.roleId });
      flash("Operator added");
      return load();
    }).then(() => setBusy(false))
      .catch((e) => { setErr(String(e.message || e)); setBusy(false); });
  };

  const patchOperator = (id, patch, msg) =>
    run(window.OfficeAPI.patchOperator(id, patch), () => flash(msg));

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Administration · onboarding</span>
          <h2 className="off-screen-title">Store setup</h2>
        </div>
        <div className="off-screen-actions">
          {savedMsg ? <span className="off-filter-count">{savedMsg}</span> : null}
          {pendingName ? <span className="off-filter-count">⚠ store name not confirmed yet</span> : null}
        </div>
      </header>

      <div className="off-screen-body" style={{ overflow: "auto", display: "grid", gap: 16 }}>
        {err ? <div className="off-card signin-error">{err}</div> : null}

        {/* --- Organisation identity --- */}
        <section className="off-card" style={{ padding: 16 }}>
          <h3 style={{ margin: "0 0 12px" }}>Organisation</h3>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
            <SetupField label="Trading name" required value={orgDraft.name}
              placeholder="e.g. Kurrajong Pharmacy" onChange={(v) => setOrgDraft({ ...orgDraft, name: v })} />
            <SetupField label="Legal name" value={orgDraft.legalName}
              placeholder="e.g. Kurrajong Pharmacy Pty Ltd" onChange={(v) => setOrgDraft({ ...orgDraft, legalName: v })} />
            <SetupField label="ABN (11 digits)" value={orgDraft.groupAbn}
              placeholder="11122233344" onChange={(v) => setOrgDraft({ ...orgDraft, groupAbn: v.replace(/\D/g, "") })} />
            <SetupField label="Timezone" value={orgDraft.timezone}
              placeholder="Australia/Sydney" onChange={(v) => setOrgDraft({ ...orgDraft, timezone: v })} />
          </div>
          <div style={{ marginTop: 12 }}>
            <button className="btn btn--primary btn--sm" disabled={busy} onClick={saveOrg}>Save organisation</button>
          </div>
        </section>

        {/* --- Site details --- */}
        {siteDraft ? (
          <section className="off-card" style={{ padding: 16 }}>
            <h3 style={{ margin: "0 0 12px" }}>Pharmacy site {siteDraft.code ? `· ${siteDraft.code}` : ""}</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
              <SetupField label="Site name" required value={siteDraft.name}
                onChange={(v) => setSiteDraft({ ...siteDraft, name: v })} />
              <SetupField label="PBS approval number" value={siteDraft.pbsApprovalNumber}
                onChange={(v) => setSiteDraft({ ...siteDraft, pbsApprovalNumber: v })} />
              <SetupField label="AHPRA pharmacy number" value={siteDraft.ahpraPharmacyNumber}
                onChange={(v) => setSiteDraft({ ...siteDraft, ahpraPharmacyNumber: v })} />
              <SetupField label="Phone" value={siteDraft.phone}
                onChange={(v) => setSiteDraft({ ...siteDraft, phone: v })} />
              <SetupField label="Email" type="email" value={siteDraft.email}
                onChange={(v) => setSiteDraft({ ...siteDraft, email: v })} />
              <SetupField label="Street address" value={siteDraft.addressLine1}
                onChange={(v) => setSiteDraft({ ...siteDraft, addressLine1: v })} />
              <SetupField label="Suburb" value={siteDraft.locality}
                onChange={(v) => setSiteDraft({ ...siteDraft, locality: v })} />
              <SetupField label="State" value={siteDraft.region}
                onChange={(v) => setSiteDraft({ ...siteDraft, region: v })} />
              <SetupField label="Postcode" value={siteDraft.postalCode}
                onChange={(v) => setSiteDraft({ ...siteDraft, postalCode: v })} />
            </div>
            <div style={{ marginTop: 12 }}>
              <button className="btn btn--primary btn--sm" disabled={busy} onClick={saveSite}>Save site</button>
            </div>
          </section>
        ) : null}

        {/* --- Roles --- */}
        <section className="off-card" style={{ padding: 16 }}>
          <h3 style={{ margin: "0 0 12px" }}>Roles</h3>
          {rolesReady ? (
            <div className="off-muted">
              {state.roles.map((r) => (
                <div key={r.id} style={{ marginBottom: 4 }}>
                  <span className="off-cell-strong">{r.name}</span> · {r.permissions.length} permission{r.permissions.length === 1 ? "" : "s"}
                </div>
              ))}
            </div>
          ) : (
            <div>
              <p className="off-muted">No roles yet. Seed the standard set (Owner, Manager, Pharmacist, Cashier) — they can be tuned later.</p>
              <button className="btn btn--primary btn--sm" disabled={busy}
                onClick={() => run(window.OfficeAPI.seedRoles(), () => flash("Standard roles created"))}>
                Seed standard roles
              </button>
            </div>
          )}
        </section>

        {/* --- Operators --- */}
        <section className="off-card" style={{ padding: 16 }}>
          <h3 style={{ margin: "0 0 12px" }}>Operators</h3>
          <p className="off-muted" style={{ marginTop: 0 }}>
            Operators sync to the tills. A PIN is set on the till at first sign-in — it is never entered here.
          </p>
          {state.operators.length > 0 ? (
            <table className="off-table" style={{ width: "100%", marginBottom: 12 }}>
              <thead>
                <tr><th>Name</th><th>Login code</th><th>Email</th><th>Role</th><th>Status</th><th></th></tr>
              </thead>
              <tbody>
                {state.operators.map((o) => (
                  <tr key={o.id}>
                    <td className="off-cell-strong">{o.displayName || `${o.firstName} ${o.lastName}`}</td>
                    <td>{o.loginCode || "—"}</td>
                    <td className="off-muted">{o.email || "—"}</td>
                    <td>
                      <select className="input select" value={o.roleId || ""} disabled={busy}
                        onChange={(e) => patchOperator(o.id, { roleId: e.target.value }, "Role updated")}>
                        {state.roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
                      </select>
                    </td>
                    <td>{o.isActive ? "Active" : "Inactive"}</td>
                    <td>
                      <button className="btn btn--ghost btn--sm" disabled={busy}
                        onClick={() => patchOperator(o.id, { isActive: !o.isActive }, o.isActive ? "Operator deactivated" : "Operator reactivated")}>
                        {o.isActive ? "Deactivate" : "Reactivate"}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <p className="off-muted">No operators yet.</p>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12, alignItems: "end" }}>
            <SetupField label="First name" required value={opDraft.firstName}
              onChange={(v) => setOpDraft({ ...opDraft, firstName: v })} />
            <SetupField label="Last name" required value={opDraft.lastName}
              onChange={(v) => setOpDraft({ ...opDraft, lastName: v })} />
            <SetupField label="Email" type="email" value={opDraft.email}
              onChange={(v) => setOpDraft({ ...opDraft, email: v })} />
            <SetupField label="Login code" value={opDraft.loginCode}
              placeholder="e.g. AK" onChange={(v) => setOpDraft({ ...opDraft, loginCode: v.toUpperCase() })} />
            <label className="field">
              <span className="field-label">Role<span className="field-required"> *</span></span>
              <select className="input select" value={opDraft.roleId}
                onChange={(e) => setOpDraft({ ...opDraft, roleId: e.target.value })}>
                <option value="">Choose…</option>
                {state.roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
              </select>
            </label>
            <button className="btn btn--primary btn--sm" disabled={busy || !rolesReady} onClick={addOperator}>
              Add operator
            </button>
          </div>
          {!rolesReady ? <p className="off-muted" style={{ marginTop: 8 }}>Seed roles first, then add operators.</p> : null}
        </section>
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  storeSetup: StoreSetupScreen,
});
