/* Admin: user management.

   List of every registered user with role + subscription chips and quick
   actions to grant/revoke a subscription or change role. Admin gate is
   enforced server-side too — non-admins hitting /api/admin/users get 403.

   Owner-only actions (Items 4 and 5):
     • Upload-grant toggle — flips can_upload. Capped at 1 non-owner uploader
       per Ishaan's spec; server returns 400 if the cap is hit.
     • Comp subscription   — bypass-payment endpoint, logs bypass_reason.
   Both buttons are hidden for non-owner admins (Ishaan = AICAN_OWNER_EMAIL).
*/
const AdminView = ({ user }) => {
  const t = window.useLanguage().t;
  const [rows, setRows]       = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');
  const [busyKey, setBusyKey] = React.useState('');  // disables the row's buttons mid-call
  const [filter, setFilter]   = React.useState('');
  const isOwner = !!(user && user.is_owner);

  const refresh = React.useCallback(async () => {
    setLoading(true); setErr('');
    try {
      const r = await window.AicanAPI.adminListUsers();
      setRows((r && r.users) || []);
    } catch (e) {
      setErr(e.message || 'Failed to load users');
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const updateUser = async (key, patch) => {
    setBusyKey(key); setErr('');
    try {
      const r = await window.AicanAPI.adminUpdateUser(key, patch);
      // Replace just this row in-place so the table doesn't flicker.
      setRows(prev => prev.map(u => u._email_key === key ? (r.user || u) : u));
    } catch (e) {
      setErr(e.message || 'Update failed');
    } finally {
      setBusyKey('');
    }
  };

  // Item 5 — owner-only comp subscription. Prompts for a free-text reason
  // (stored on the user record as payment_bypass.reason for audit).
  const bypassPayment = async (key, displayName) => {
    const reason = window.prompt(
      t('Reason for waiving payment for') + ` ${displayName}?\n` +
      t('This is logged for audit (e.g. "VIP partner", "trial extension").'),
      ''
    );
    if (reason === null) return; // user cancelled
    setBusyKey(key); setErr('');
    try {
      const r = await window.AicanAPI.adminBypassPayment(key, reason);
      setRows(prev => prev.map(u => u._email_key === key ? (r.user || u) : u));
    } catch (e) {
      setErr(e.message || 'Bypass failed');
    } finally {
      setBusyKey('');
    }
  };

  const visible = rows.filter(u => {
    if (!filter) return true;
    const f = filter.toLowerCase();
    return (u.email || '').toLowerCase().includes(f)
        || (u.name  || '').toLowerCase().includes(f)
        || (u.medical_reg_no || '').toLowerCase().includes(f)
        || (u.role  || '').toLowerCase().includes(f);
  });

  const subChip = (s) => s === 'active'
    ? <span className="chip accent">{t('Active')}</span>
    : <span className="chip warn">{t('Inactive')}</span>;

  const roleChip = (r) => {
    const map = { admin: 'crit', doctor: 'info', patient: 'neutral' };
    return <span className={"chip " + (map[r] || 'neutral')}>{(r || '?').toUpperCase()}</span>;
  };

  // Access-control status (Item 3). Legacy rows without the field read as
  // "approved" (matches the backend's grandfathering in _public_user).
  const accessChip = (a) => {
    const v = a || 'approved';
    const map   = { approved: 'ok', pending: 'warn', denied: 'crit' };
    const label = { approved: t('Approved'), pending: t('Pending'), denied: t('Denied') };
    return <span className={"chip " + (map[v] || 'neutral')}>{label[v] || v}</span>;
  };

  return (
    <div className="worklist">
      <div className="header">
        <h1>{t('Admin · Users')}</h1>
        <span className="mono" style={{fontSize:15, color:'var(--fg-3)'}}>
          {visible.length} / {rows.length} {t('users')}
        </span>
      </div>

      <div className="filters">
        <div className="search">
          <IconSearch/>
          <input className="input"
            placeholder={t('Search · name, email, role…')}
            value={filter} onChange={(e) => setFilter(e.target.value)}/>
        </div>
        <div style={{flex:1}}/>
        <button className="btn ghost sm" onClick={refresh} disabled={loading}>
          {loading ? t('Loading…') : '↻ ' + t('Refresh')}
        </button>
      </div>

      {err && (
        <div style={{margin:'8px 0', padding:'10px 12px', borderRadius:7,
          background:'rgba(220,38,38,0.08)', color:'#b91c1c',
          border:'1px solid rgba(220,38,38,0.25)', fontSize:17}}>{err}</div>
      )}

      <table className="t">
        <thead>
          <tr>
            <th>{t('Name')}</th>
            <th>{t('Email')}</th>
            <th>{t('Medical Reg. No')}</th>
            <th>{t('Role')}</th>
            <th>{t('Access')}</th>
            <th>{t('Subscription')}</th>
            <th>{t('Upload')}</th>
            <th>{t('Created')}</th>
            <th style={{textAlign:'right'}}>{t('Actions')}</th>
          </tr>
        </thead>
        <tbody>
          {visible.map(u => {
            const k = u._email_key;
            const busy = busyKey === k;
            const sub = u.subscription_status || 'active';
            return (
              <tr key={k}>
                <td>
                  <div style={{fontWeight:600}}>{u.name || '—'}</div>
                  <div style={{fontSize:15, color:'var(--fg-3)'}}>
                    {u.is_admin ? '★ ' : ''}{u.google_sub ? 'Google · ' : ''}
                    {u.created_at ? new Date(u.created_at * 1000).toLocaleDateString() : ''}
                  </div>
                </td>
                <td className="mono" style={{fontSize:16}}>{u.email}</td>
                <td className="mono" style={{fontSize:16}} title={t('Verify against the medical council registry before approving')}>{u.medical_reg_no || '—'}</td>
                <td>{roleChip(u.role)}</td>
                <td>{accessChip(u.access_status)}</td>
                <td>{subChip(sub)}</td>
                <td>
                  {/* Item 4 — upload permission chip. Owner is implicit
                      (always allowed); show "OWNER" for them so the row
                      isn't ambiguous. */}
                  {u.is_owner
                    ? <span className="chip crit">{t('OWNER')}</span>
                    : (u.can_upload
                        ? <span className="chip ok">{t('Granted')}</span>
                        : <span className="chip neutral">{t('No')}</span>)}
                </td>
                <td className="mono" style={{fontSize:15, color:'var(--fg-2)'}}>
                  {u.created_at ? new Date(u.created_at * 1000).toLocaleString() : '—'}
                </td>
                <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                  {/* Access approval (Item 3). Hidden for admins — they're
                      always approved server-side, so the buttons would be
                      no-ops. */}
                  {!u.is_admin && (
                    (u.access_status || 'approved') === 'approved' ? (
                      <button className="btn ghost sm" disabled={busy}
                        onClick={() => updateUser(k, { access_status: 'denied' })}
                        style={{marginRight:4}} title={t('Block this account')}>
                        {t('Block')}
                      </button>
                    ) : (
                      <button className="btn primary sm" disabled={busy}
                        onClick={() => updateUser(k, { access_status: 'approved' })}
                        style={{marginRight:4}} title={t('Approve this account')}>
                        {t('Approve')}
                      </button>
                    )
                  )}
                  {/* Subscription toggle */}
                  {sub === 'active' ? (
                    <button className="btn ghost sm" disabled={busy}
                      onClick={() => updateUser(k, { subscription_status: 'inactive' })}
                      style={{marginRight:4}}>
                      {t('Revoke')}
                    </button>
                  ) : (
                    <button className="btn primary sm" disabled={busy}
                      onClick={() => updateUser(k, { subscription_status: 'active' })}
                      style={{marginRight:4}}>
                      {t('Grant')}
                    </button>
                  )}
                  {/* Item 4 — Upload grant toggle (owner-only). Hidden for
                      the owner row itself (always allowed) and shown as a
                      tooltip-disabled button for non-owner admins. */}
                  {isOwner && !u.is_owner && (
                    u.can_upload ? (
                      <button className="btn ghost sm" disabled={busy}
                        onClick={() => updateUser(k, { can_upload: false })}
                        style={{marginRight:4}}
                        title={t('Revoke upload permission')}>
                        {t('Revoke Upload')}
                      </button>
                    ) : (
                      <button className="btn primary sm" disabled={busy}
                        onClick={() => updateUser(k, { can_upload: true })}
                        style={{marginRight:4}}
                        title={t('Grant upload permission (max 1 non-owner)')}>
                        {t('Grant Upload')}
                      </button>
                    )
                  )}
                  {/* Item 5 — owner-only comp subscription (bypass payment). */}
                  {isOwner && !u.is_owner && sub !== 'active' && (
                    <button className="btn ghost sm" disabled={busy}
                      onClick={() => bypassPayment(k, u.name || u.email)}
                      style={{marginRight:4}}
                      title={t('Comp this account — bypass payment with reason logged')}>
                      {t('Comp')}
                    </button>
                  )}
                  {/* Role select (lightweight inline editor) */}
                  <select
                    className="input"
                    style={{padding:'4px 6px', fontSize:16, width:90}}
                    value={u.role || 'doctor'}
                    disabled={busy}
                    onChange={(e) => updateUser(k, { role: e.target.value })}
                    title={t('Change role')}
                  >
                    <option value="patient">{t('Patient')}</option>
                    <option value="doctor">{t('Doctor')}</option>
                    <option value="admin">{t('Admin')}</option>
                  </select>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      {!loading && rows.length === 0 && (
        <div style={{padding:'24px', textAlign:'center', color:'var(--fg-3)'}}>
          {t('No users yet.')}
        </div>
      )}
    </div>
  );
};

window.AdminView = AdminView;
