/* ==================================================================
   Admin → Personnel
   ------------------------------------------------------------------
   Manage non-teaching support staff (drivers, sweepers, guards, …) and
   the duties they perform. A person can hold several duties. When "driver"
   is one of them, the staffer can sign into the bus driver app and pick a
   bus when they start a journey.
   Creates a support_staff user + login credentials in one go (the temp
   password is shown once, to hand over).
   ================================================================== */

const { Icon: PsIcon } = window.KXUI;

const PERSONNEL_DUTIES = [
  "driver", "sweeper", "marketing", "electrician", "plumber",
  "guard", "gateman", "cook", "helper",
];
const dutyLabel = (d) => d.charAt(0).toUpperCase() + d.slice(1);

// Multi-select duty chips.
const DutyChips = ({ value, onChange }) => {
  const toggle = (d) => {
    const set = new Set(value);
    set.has(d) ? set.delete(d) : set.add(d);
    onChange(Array.from(set));
  };
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
      {PERSONNEL_DUTIES.map((d) => {
        const on = value.includes(d);
        return (
          <button key={d} type="button" onClick={() => toggle(d)}
            style={{
              padding: "5px 12px", borderRadius: 999, fontSize: 12,
              border: `1px solid ${on ? "var(--accent)" : "var(--line-strong)"}`,
              background: on ? "rgba(255,186,90,0.14)" : "var(--bg-2)",
              color: on ? "var(--accent)" : "var(--ink-1)", cursor: "pointer",
            }}>
            {d === "driver" ? "🚌 " : ""}{dutyLabel(d)}
          </button>
        );
      })}
    </div>
  );
};

const PersonnelScreen = () => {
  const [list, setList] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [form, setForm] = React.useState({ name: "", phone: "", email: "", password: "", duties: [] });
  const [flash, setFlash] = React.useState(null);          // { name, username, temp_password }
  const [editId, setEditId] = React.useState(null);        // row being duty-edited
  const [editDuties, setEditDuties] = React.useState([]);

  const load = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try { setList((await window.KXApi.get("/admin/personnel")).personnel || []); }
    catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  }, []);
  React.useEffect(() => { load(); }, [load]);

  async function create(e) {
    e.preventDefault();
    setErr(null);
    if (!form.name.trim() || !form.phone.trim()) { setErr("Name and phone are required."); return; }
    try {
      const out = await window.KXApi.post("/admin/personnel", {
        name: form.name.trim(), phone: form.phone.trim(),
        email: form.email.trim() || undefined,
        password: form.password.trim() || undefined,
        duties: form.duties,
      });
      setFlash({ name: out.name, username: out.username, temp_password: out.temp_password });
      setForm({ name: "", phone: "", email: "", password: "", duties: [] });
      setAdding(false);
      load();
    } catch (e) {
      setErr(e.message.includes("phone already") ? "That phone is already registered."
        : e.message.includes("email already") ? "That email is already registered."
        : e.message);
    }
  }

  async function resetPw(p) {
    try {
      const out = await window.KXApi.post(`/admin/personnel/${p.id}/reset-password`, {});
      setFlash({ name: p.name, username: p.username, temp_password: out.temp_password });
    } catch (e) { setErr(e.message); }
  }
  async function toggleActive(p) {
    try {
      if (p.active) await window.KXApi.del(`/admin/personnel/${p.id}`);
      else await window.KXApi.patch(`/admin/personnel/${p.id}`, { active: true });
      load();
    } catch (e) { setErr(e.message); }
  }
  function startEditDuties(p) { setEditId(p.id); setEditDuties(p.duties || []); }
  async function saveDuties(p) {
    try { await window.KXApi.patch(`/admin/personnel/${p.id}`, { duties: editDuties }); setEditId(null); load(); }
    catch (e) { setErr(e.message); }
  }

  return (
    <div className="cx-page" style={{ maxWidth: 1100 }}>
      <div className="cx-page-head">
        <div>
          <div className="cx-eyebrow">Admin · support staff</div>
          <h1 className="cx-h1">Personnel</h1>
          <p style={{ margin: "8px 0 0", color: "var(--ink-3)", fontSize: 13.5, maxWidth: 620 }}>
            Support staff and their duties. Drivers sign into the bus app with the username + password below.
          </p>
        </div>
        {!adding && <button className="cx-btn-dark" onClick={() => { setAdding(true); setFlash(null); }}>
          <PsIcon name="plus" size={14} /> Add personnel
        </button>}
      </div>

      {/* One-time credentials flash */}
      {flash && (
        <div style={{ background: "rgba(75,201,123,0.10)", border: "1px solid rgba(75,201,123,0.4)",
          borderRadius: 8, padding: "12px 14px", marginBottom: 16 }}>
          <div style={{ color: "var(--ink-0)", fontSize: 13, fontWeight: 600 }}>Login for {flash.name}</div>
          <div style={{ color: "var(--ink-1)", fontSize: 13, marginTop: 4 }}>
            Username: <b>{flash.username}</b> &nbsp;·&nbsp; Temp password: <b>{flash.temp_password}</b>
          </div>
          <div style={{ color: "var(--ink-3)", fontSize: 11, marginTop: 4 }}>
            Shown once — hand these to the staffer. They sign in at the driver app with the username (or phone) + this password.
          </div>
          <button className="btn ghost sm" style={{ marginTop: 8 }} onClick={() => setFlash(null)}>Dismiss</button>
        </div>
      )}

      {/* Add form */}
      {adding && (
        <form onSubmit={create} className="card" style={{ background: "var(--bg-2)", border: "1px solid var(--line)",
          borderRadius: 10, padding: 16, marginBottom: 16 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <label style={{ fontSize: 11, color: "var(--ink-2)" }}>Name
              <input className="input" style={{ display: "block", width: "100%" }} value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Full name" />
            </label>
            <label style={{ fontSize: 11, color: "var(--ink-2)" }}>Phone (WhatsApp)
              <input className="input" style={{ display: "block", width: "100%" }} value={form.phone}
                onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="10-digit number" />
            </label>
            <label style={{ fontSize: 11, color: "var(--ink-2)" }}>Email <span className="muted">(optional)</span>
              <input className="input" style={{ display: "block", width: "100%" }} value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </label>
            <label style={{ fontSize: 11, color: "var(--ink-2)" }}>Password <span className="muted">(blank = auto)</span>
              <input className="input" style={{ display: "block", width: "100%" }} value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="Auto-generated if blank" />
            </label>
          </div>
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 11, color: "var(--ink-2)", marginBottom: 6 }}>DUTIES (pick one or more)</div>
            <DutyChips value={form.duties} onChange={(d) => setForm({ ...form, duties: d })} />
            {form.duties.includes("driver") && (
              <p style={{ color: "var(--ink-3)", fontSize: 11, marginTop: 8 }}>
                🚌 As a driver, they'll choose which bus to take when they start a journey in the driver app — and every
                parent on that bus is notified automatically.
              </p>
            )}
          </div>
          {err && <div style={{ color: "var(--red)", fontSize: 12, marginTop: 10 }}>{err}</div>}
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button type="submit" className="btn primary">Create personnel</button>
            <button type="button" className="btn ghost" onClick={() => { setAdding(false); setErr(null); }}>Cancel</button>
          </div>
        </form>
      )}

      {err && !adding && <div style={{ color: "var(--red)", fontSize: 12, marginBottom: 10 }}>{err}</div>}

      {/* List */}
      {loading ? <div className="muted">Loading…</div> : list.length === 0 ? (
        <div className="muted" style={{ fontSize: 13 }}>No personnel yet — add your first support-staff member above.</div>
      ) : (
        <div className="cx-tablecard">
        <div className="cx-tablescroll">
        <table className="cx-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Login</th>
              <th>Duties</th>
              <th className="actions">Actions</th>
            </tr>
          </thead>
          <tbody>
            {list.map((p) => (
              <tr key={p.id} className={p.active ? "" : "muted-row"}>
                <td>
                  <div className="t-main">{p.name}</div>
                  {p.phone && <div className="t-sub">{p.phone}</div>}
                </td>
                <td><span className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>{p.username || "—"}</span></td>
                <td>
                  {editId === p.id ? (
                    <div>
                      <DutyChips value={editDuties} onChange={setEditDuties} />
                      <div style={{ marginTop: 8 }}>
                        <button className="btn primary sm" onClick={() => saveDuties(p)}>Save</button>{" "}
                        <button className="btn ghost sm" onClick={() => setEditId(null)}>Cancel</button>
                      </div>
                    </div>
                  ) : (
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 4, alignItems: "center" }}>
                      {(p.duties || []).length === 0 && <span className="muted" style={{ fontSize: 12 }}>—</span>}
                      {(p.duties || []).map((d) => (
                        <span key={d} className="pill" style={{ fontSize: 10 }}>
                          {d === "driver" ? "🚌 " : ""}{dutyLabel(d)}
                        </span>
                      ))}
                      <button className="btn sm" style={{ marginLeft: 4 }} onClick={() => startEditDuties(p)}>Edit</button>
                    </div>
                  )}
                </td>
                <td className="actions">
                  <button className="btn sm" onClick={() => resetPw(p)}>Reset password</button>{" "}
                  <button className={`btn sm ${p.active ? "danger" : ""}`} onClick={() => toggleActive(p)}>
                    {p.active ? "Disable" : "Enable"}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
        </div>
      )}
    </div>
  );
};

window.PersonnelScreen = PersonnelScreen;
