// PendingApprovals — Admin page to review self-registration requests
// Exports: PendingApprovals

function PendingApprovals() {
  const [users, setUsers]       = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [flash, setFlash]       = React.useState(null);
  const [rejectTarget, setRejectTarget] = React.useState(null); // { id, name }
  const [rejectReason, setRejectReason] = React.useState('');
  const [acting, setActing]     = React.useState(null); // id currently being processed

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }

  async function fetchPending() {
    setLoading(true);
    try {
      const res = await fetch('/api/users/pending', { headers: authH() });
      setUsers(res.ok ? await res.json() : []);
    } catch { setUsers([]); }
    finally { setLoading(false); }
  }

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

  function showFlash(type, text) {
    setFlash({ type, text });
    setTimeout(() => setFlash(null), 5000);
  }

  function fmtDate(val) {
    if (!val) return '—';
    try { return new Date(val).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); }
    catch { return val; }
  }

  async function approve(user) {
    setActing(user.id);
    try {
      const res  = await fetch(`/api/users/${user.id}/approve`, { method: 'POST', headers: authH() });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      showFlash('success', `${user.name} approved — they'll receive a confirmation email.`);
      fetchPending();
    } catch (e) { showFlash('error', e.message || 'Approval failed'); }
    finally { setActing(null); }
  }

  async function reject() {
    if (!rejectTarget) return;
    setActing(rejectTarget.id);
    try {
      const res  = await fetch(`/api/users/${rejectTarget.id}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ reason: rejectReason.trim() }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      showFlash('success', `${rejectTarget.name}'s request was rejected.`);
      setRejectTarget(null); setRejectReason('');
      fetchPending();
    } catch (e) { showFlash('error', e.message || 'Rejection failed'); }
    finally { setActing(null); }
  }

  const isMobile = window.useIsMobile ? useIsMobile() : false;

  return (
    <div>
      {/* Flash */}
      {flash && (
        <div style={{
          marginBottom: 18, padding: '12px 16px', borderRadius: 10, fontSize: 13, fontWeight: 600,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>
          {flash.type === 'success' ? '✓ ' : '✗ '}{flash.text}
        </div>
      )}

      {/* Summary stat */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '18px 22px', display: 'flex', alignItems: 'center', gap: 14, minWidth: 180 }}>
          <div style={{ width: 42, height: 42, borderRadius: 10, background: '#FFF7ED', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <IC name="clock" size={20} color="#D97706" />
          </div>
          <div>
            <div style={{ fontSize: 28, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{loading ? '…' : users.length}</div>
            <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 4 }}>Awaiting review</div>
          </div>
        </div>
      </div>

      {/* Table card */}
      <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{ padding: '16px 22px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 15 }}>Registration Requests</div>
            <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>
              {loading ? 'Loading…' : users.length === 0 ? 'No pending requests' : `${users.length} request${users.length === 1 ? '' : 's'} waiting for approval`}
            </div>
          </div>
          <button onClick={fetchPending} title="Refresh" style={{
            background: 'none', border: '1.5px solid #E2E8F0', borderRadius: 8, cursor: 'pointer',
            padding: '6px 10px', display: 'flex', alignItems: 'center', gap: 6, color: '#64748B', fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>
            <IC name="refresh" size={13} color="#64748B" /> Refresh
          </button>
        </div>

        {/* Column headers — desktop only */}
        {!isMobile && !loading && users.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 120px 180px', gap: 12, padding: '8px 22px', background: '#F8FAFC', borderBottom: '1px solid #F1F5F9' }}>
            {['Name', 'Email', 'Requested', 'Actions'].map((h, i) => (
              <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em', textAlign: i === 3 ? 'right' : 'left' }}>{h}</span>
            ))}
          </div>
        )}

        {/* Rows */}
        {loading ? (
          <div style={{ padding: '40px 22px', textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Loading…</div>
        ) : users.length === 0 ? (
          <div style={{ padding: '56px 22px', textAlign: 'center' }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: '#F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
              <IC name="check" size={24} color="#10B981" />
            </div>
            <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 15, marginBottom: 6 }}>All caught up!</div>
            <div style={{ fontSize: 13, color: '#94A3B8' }}>No pending registration requests at the moment.</div>
          </div>
        ) : users.map((u, i) => {
          const isActing = acting === u.id;
          if (isMobile) return (
            <div key={u.id} style={{ padding: '14px 16px', borderBottom: i < users.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 10 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 14, color: '#0F172A', marginBottom: 2 }}>{u.name}</div>
                  <div style={{ fontSize: 12, color: '#64748B', marginBottom: 4 }}>{u.email}</div>
                  <div style={{ fontSize: 11, color: '#94A3B8' }}>Requested {fmtDate(u.created_at)}</div>
                </div>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: '#FFF7ED', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <IC name="userplus" size={18} color="#D97706" />
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button disabled={isActing} onClick={() => approve(u)} style={{
                  flex: 1, padding: '9px', borderRadius: 8, border: 'none', cursor: isActing ? 'wait' : 'pointer',
                  background: '#10B981', color: '#fff', fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
                  opacity: isActing ? 0.6 : 1, transition: 'opacity 0.15s',
                }}>
                  {isActing ? '…' : 'Approve'}
                </button>
                <button disabled={isActing} onClick={() => { setRejectTarget(u); setRejectReason(''); }} style={{
                  flex: 1, padding: '9px', borderRadius: 8, border: '1.5px solid #FCA5A5', cursor: isActing ? 'wait' : 'pointer',
                  background: '#FFF', color: '#DC2626', fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
                  opacity: isActing ? 0.6 : 1, transition: 'opacity 0.15s',
                }}>
                  Reject
                </button>
              </div>
            </div>
          );
          return (
            <div key={u.id} style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr 120px 180px', gap: 12,
              padding: '14px 22px', alignItems: 'center',
              borderBottom: i < users.length - 1 ? '1px solid #F8FAFC' : 'none',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Avatar name={u.name} initials={u.name.split(' ').map(n => n[0]).join('').slice(0,2).toUpperCase()} size={34} />
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13, color: '#0F172A' }}>{u.name}</div>
                  <div style={{ fontSize: 11, color: '#94A3B8' }}>Self-registered</div>
                </div>
              </div>
              <div style={{ fontSize: 13, color: '#475569', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</div>
              <div style={{ fontSize: 12, color: '#64748B' }}>{fmtDate(u.created_at)}</div>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <button disabled={isActing} onClick={() => approve(u)} style={{
                  padding: '7px 14px', borderRadius: 7, border: 'none', cursor: isActing ? 'wait' : 'pointer',
                  background: '#10B981', color: '#fff', fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
                  opacity: isActing ? 0.6 : 1, transition: 'opacity 0.15s', whiteSpace: 'nowrap',
                }}>
                  {isActing ? '…' : '✓ Approve'}
                </button>
                <button disabled={isActing} onClick={() => { setRejectTarget(u); setRejectReason(''); }} style={{
                  padding: '7px 14px', borderRadius: 7, border: '1.5px solid #FCA5A5', cursor: isActing ? 'wait' : 'pointer',
                  background: '#fff', color: '#DC2626', fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
                  opacity: isActing ? 0.6 : 1, transition: 'opacity 0.15s', whiteSpace: 'nowrap',
                }}>
                  ✕ Reject
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* Reject modal */}
      {rejectTarget && (
        <div onClick={(e) => { if (e.target === e.currentTarget) { setRejectTarget(null); setRejectReason(''); } }} style={{
          position: 'fixed', inset: 0, background: 'rgba(15,37,64,0.5)', zIndex: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
        }}>
          <div style={{ background: '#fff', borderRadius: 16, padding: '28px 28px 24px', width: '100%', maxWidth: 420, boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}>
            <div style={{ fontWeight: 800, fontSize: 18, color: '#0F172A', marginBottom: 6 }}>Reject Request</div>
            <div style={{ fontSize: 13, color: '#64748B', marginBottom: 20 }}>
              You are rejecting <strong style={{ color: '#0F172A' }}>{rejectTarget.name}</strong> ({rejectTarget.email}).
              They will receive an email notification.
            </div>
            <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>
              Reason <span style={{ fontWeight: 400, color: '#94A3B8', textTransform: 'none', letterSpacing: 0 }}>(optional)</span>
            </label>
            <textarea
              value={rejectReason}
              onChange={e => setRejectReason(e.target.value)}
              placeholder="e.g. Not affiliated with our organisation"
              rows={3}
              style={{
                width: '100%', padding: '10px 12px', border: '1.5px solid #E2E8F0', borderRadius: 8,
                fontFamily: 'inherit', fontSize: 14, color: '#1E293B', resize: 'none', outline: 'none',
                marginBottom: 20,
              }}
            />
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button onClick={() => { setRejectTarget(null); setRejectReason(''); }} style={{
                padding: '9px 18px', borderRadius: 8, border: '1.5px solid #E2E8F0', background: '#fff',
                color: '#374151', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>Cancel</button>
              <button onClick={reject} disabled={acting === rejectTarget.id} style={{
                padding: '9px 18px', borderRadius: 8, border: 'none', background: '#DC2626',
                color: '#fff', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: acting ? 'wait' : 'pointer',
                opacity: acting ? 0.6 : 1,
              }}>
                {acting === rejectTarget.id ? 'Rejecting…' : 'Reject Request'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PendingApprovals });
