// ============================================================
// GESTIONE ACCESSI — sezione admin per le credenziali di
// dottori e pazienti (username + reset password). La password
// non è mai visibile: si può solo reimpostare.
// ============================================================
function CredRow({ account, kind, currentDocId, onSaved }) {
  const [username, setUsername] = useState(account.username || "");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState(null); // { type: "ok"|"err", text }

  const isSelf = kind === "doctor" && account.id === currentDocId;
  const normUser = username.trim().toLowerCase();
  const changedUser = normUser && normUser !== (account.username || "");
  const dirty = changedUser || password.length > 0;

  const save = async () => {
    if (!dirty || busy) return;
    setBusy(true); setMsg(null);
    const creds = {};
    if (changedUser) creds.username = normUser;
    if (password) creds.password = password;
    try {
      const api = kind === "doctor" ? window.NefroAPI.setDoctorCredentials : window.NefroAPI.setPatientCredentials;
      await api(account.id, creds);
      if (creds.username) { account.username = creds.username; setUsername(creds.username); }
      setPassword("");
      setMsg({ type: "ok", text: "Salvato" });
      onSaved && onSaved(kind, account.id, account.username);
      setTimeout(() => setMsg(null), 2500);
    } catch (e) {
      setMsg({ type: "err", text: e.message });
    } finally { setBusy(false); }
  };

  const meta = kind === "doctor" ? (account.ruolo || "Medico") : `${account.stadio || ""}${account.eta ? " · " + account.eta + " anni" : ""}`;

  return (
    <div className="cred-row">
      <div className="cred-who">
        <Avatar nome={account.nome} cognome={account.cognome} hue={account.avatarHue ?? 250} size={38} />
        <div>
          <div className="cred-name">{account.nome} {account.cognome}{isSelf && <span className="cred-you"> · tu</span>}</div>
          <div className="cred-meta">{meta}</div>
        </div>
      </div>
      <label className="cred-field">
        <span className="cred-flabel">Username</span>
        <input className="field-input" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="nome.cognome" autoComplete="off" />
      </label>
      <label className="cred-field">
        <span className="cred-flabel">Nuova password</span>
        <input className="field-input" type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="lascia vuoto per non cambiarla" autoComplete="new-password" />
      </label>
      <div className="cred-actions">
        <button className={`btn btn-primary ${dirty && !busy ? "" : "btn-disabled"}`} disabled={!dirty || busy} onClick={save}>
          {busy ? "…" : "Salva"}
        </button>
        {msg && <span className={`cred-msg ${msg.type === "ok" ? "cred-ok" : "cred-err"}`}>{msg.text}</span>}
      </div>
    </div>
  );
}

function CredentialsView({ doctors, patients, currentDocId, onSaved }) {
  const [q, setQ] = useState("");
  const match = (a) => (a.nome + " " + a.cognome + " " + (a.username || "")).toLowerCase().includes(q.toLowerCase());
  const docs = doctors.filter(match);
  const pts = patients.filter(match);
  return (
    <div className="main">
      <div className="content">
        <div className="panel">
          <div className="panel-head">
            <div>
              <h3 className="panel-title" style={{ fontSize: "20px", fontFamily: "\"Open Sans\"" }}>Gestione accessi</h3>
              <p className="panel-sub">Username e password di accesso di medici e pazienti. La password non è mai leggibile: si può solo reimpostare.</p>
            </div>
            <div className="side-search" style={{ margin: 0, minWidth: 220 }}>
              <Icon name="search" size={16} />
              <input placeholder="Cerca per nome o username…" value={q} onChange={(e) => setQ(e.target.value)} />
            </div>
          </div>

          <div className="cred-section-title"><Icon name="users" size={15} /> Medici <span className="cred-count">{docs.length}</span></div>
          <div className="cred-list">
            {docs.map((d) => <CredRow key={d.id} account={d} kind="doctor" currentDocId={currentDocId} onSaved={onSaved} />)}
            {!docs.length && <div className="add-empty">Nessun medico.</div>}
          </div>

          <div className="cred-section-title" style={{ marginTop: 22 }}><Icon name="users" size={15} /> Pazienti <span className="cred-count">{pts.length}</span></div>
          <div className="cred-list">
            {pts.map((p) => <CredRow key={p.id} account={p} kind="patient" onSaved={onSaved} />)}
            {!pts.length && <div className="add-empty">Nessun paziente.</div>}
          </div>

          <p className="form-hint" style={{ marginTop: 18 }}><Icon name="alert" size={13} /> Password iniziali di default: «dottore» per i medici, «paziente» per i pazienti. Comunicale agli interessati e invitali a cambiarle al primo accesso.</p>
        </div>
      </div>
    </div>
  );
}
window.CredentialsView = CredentialsView;
