// User management — list accounts, add/invite users, set role (Admin/User), remove.
// Admin-only. Operates on the account store directly (changes save immediately).
function UsersManager({ accounts, setAccounts, currentUser, churchName, emailConfig }){
  const [email, setEmail] = React.useState('');
  const [name, setName] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [role, setRole] = React.useState('user');
  const [msg, setMsg] = React.useState('');

  const users = (accounts && accounts.users) || [];
  const ec = emailConfig || {};
  const emailjsReady = !!(window.emailjs && ec.emailjsKey && ec.emailjsService && ec.emailjsTemplate);

  function commit(next){ window.saveAccounts(next); setAccounts({ ...next }); }

  function inviteParams(em, password, r){
    const church = churchName || 'our church';
    const url = window.location.origin + window.location.pathname;
    const inviter = (currentUser && (currentUser.name || currentUser.email)) || 'An administrator';
    return {
      to_email: em, email: em, user_email: em,
      church, church_name: church,
      site_url: url, link: url,
      inviter_name: inviter,
      temp_password: password, role: window.roleLabel(r),
      subject: `You're invited to join ${church} on Worship Management`,
      message:
        `${inviter} has invited you to join ${church} on Worship Management as a ${window.roleLabel(r)}.\n\n` +
        `Open the church platform here: ${url}\n` +
        `Sign in with:\n  Email: ${em}\n  Temporary password: ${password}\n\n` +
        `After signing in, please change your password. Welcome to ${church}!`
    };
  }

  function mailtoInvite(em, password, r){
    const p = inviteParams(em, password, r);
    const body =
      `Hello,\n\n` +
      `${p.inviter_name} has invited you to join ${p.church} on Worship Management as a ${p.role}.\n\n` +
      `Join here: ${p.site_url}\n\n` +
      `Sign in with:\n  Email: ${em}\n  Temporary password: ${password}\n\n` +
      `After signing in, please change your password.\n\nWelcome to ${p.church}!`;
    window.location.href = `mailto:${em}?subject=${encodeURIComponent(p.subject)}&body=${encodeURIComponent(body)}`;
  }

  function sendInvite(em, password, r){
    if(emailjsReady){
      setMsg('Sending invite email to ' + em + '\u2026');
      window.emailjs.send(ec.emailjsService, ec.emailjsTemplate, inviteParams(em, password, r), { publicKey: ec.emailjsKey })
        .then(()=> setMsg('\u2713 Invite email sent to ' + em + '.'))
        .catch((e)=>{ setMsg('Could not auto-send (check EmailJS keys). Opening your mail app instead\u2026'); setTimeout(()=>mailtoInvite(em,password,r), 400); });
    } else {
      mailtoInvite(em, password, r);
    }
  }

  function add(e){
    e && e.preventDefault();
    setMsg('');
    const em = email.trim().toLowerCase();
    if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(em)){ setMsg('Enter a valid email address.'); return; }
    if(window.findUser(accounts, em)){ setMsg('That email already has an account.'); return; }
    if(pw.length < 4){ setMsg('Set a temporary password (4+ characters).'); return; }
    const next = { ...accounts, users: [...users, { email: em, name: name.trim()||em.split('@')[0], role, password: pw }] };
    commit(next);
    const addedRole = role, addedPw = pw;
    setEmail(''); setName(''); setPw(''); setRole('user');
    setMsg('Added ' + em + ' as ' + window.roleLabel(addedRole) + '.');
    setTimeout(()=> sendInvite(em, addedPw, addedRole), 150);
  }
  function changeRole(em, r){
    const next = { ...accounts, users: users.map(u => u.email===em ? { ...u, role:r } : u) };
    commit(next);
  }
  function remove(em){
    const next = { ...accounts, users: users.filter(u => u.email!==em) };
    commit(next);
  }

  return (
    <div className="users-mgr">
      <div className="users-list">
        {users.map(u=>{
          const isSuper = u.role==='superadmin';
          return (
            <div className="user-row" key={u.email}>
              <div className="user-id">
                <div className="user-em">{u.email}</div>
                <div className="user-nm">{u.name}{u.email===currentUser.email ? ' · you' : ''}</div>
              </div>
              {isSuper
                ? <span className="user-badge">Main Admin</span>
                : <select className="user-role" value={u.role} onChange={e=>changeRole(u.email, e.target.value)}>
                    <option value="admin">Admin</option>
                    <option value="user">User</option>
                  </select>}
              {isSuper
                ? <span className="user-x lock" title="Cannot be removed">{'\u25cf'}</span>
                : <React.Fragment>
                    <button className="user-mail" title="Send invite email" onClick={()=>sendInvite(u.email, u.password, u.role)}>{'\u2709'}</button>
                    <button className="user-x" title="Remove user" onClick={()=>remove(u.email)}>{'\u00d7'}</button>
                  </React.Fragment>}
            </div>
          );
        })}
      </div>

      <form className="user-add" onSubmit={add}>
        <div className="ua-title">Invite / Add User</div>
        <input className="field" placeholder="Personal email (e.g. name@gmail.com)" value={email} onChange={e=>setEmail(e.target.value)} />
        <div className="ua-row">
          <input className="field" placeholder="Display name (optional)" value={name} onChange={e=>setName(e.target.value)} />
          <input className="field" placeholder="Temp password" value={pw} onChange={e=>setPw(e.target.value)} />
        </div>
        <div className="ua-row">
          <div className="ua-roles">
            <button type="button" className={role==='admin'?'on':''} onClick={()=>setRole('admin')}>Admin</button>
            <button type="button" className={role==='user'?'on':''} onClick={()=>setRole('user')}>User</button>
          </div>
          <button className="pill sm" type="submit">Add User</button>
        </div>
        {msg && <div className="ua-msg">{msg}</div>}
        <div className="ua-hint">{emailjsReady
          ? 'Invites are emailed automatically when you add a user. Use the \u2709 button to resend.'
          : 'Set up automatic email in Settings \u2192 Email Invites. Until then, Add User opens a ready-to-send email in your mail app. Use the \u2709 button to resend.'}</div>
      </form>
    </div>
  );
}
window.UsersManager = UsersManager;
