// ── Services Page ────────────────────────────────────────────────────────

function ServicesPage() {
  const [services, setServices] = useState([]);
  useEffect(() => { api('/api/services').then(setServices).catch(() => {}); }, []);

  return (
    <>
      <h2>Services</h2>
      <div className="page-sub">Platform services and their current status</div>
      <div className="cards">
        {services.map(s => (
          <div className="card" key={s.id}>
            <div className="card-header">
              <h3>{s.name}</h3>
              <span className={`badge badge-${s.status}`}>{s.status}</span>
            </div>
            <p>{s.description}</p>
            {s.url && <a href={s.url} className="card-url" target="_blank" rel="noopener">{s.url}</a>}
          </div>
        ))}
      </div>
    </>
  );
}

// ── Profile Page ─────────────────────────────────────────────────────────

function ProfilePage({ user, setUser }) {
  const [name, setName]     = useState(user.name || '');
  const [email, setEmail]   = useState(user.email || '');
  const [saved, setSaved]   = useState(false);

  const [curPw, setCurPw]   = useState('');
  const [newPw, setNewPw]   = useState('');
  const [confPw, setConfPw] = useState('');
  const [pwMsg, setPwMsg]   = useState('');
  const [pwErr, setPwErr]   = useState('');
  const [pwBusy, setPwBusy] = useState(false);

  const saveProfile = async (e) => {
    e.preventDefault();
    try {
      const updated = await api('/api/me', { method: 'PUT', body: JSON.stringify({ name, email }) });
      setUser(u => ({ ...u, ...updated }));
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch {}
  };

  const changePassword = async (e) => {
    e.preventDefault();
    setPwErr(''); setPwMsg('');
    if (newPw !== confPw) { setPwErr('Passwords do not match'); return; }
    setPwBusy(true);
    try {
      await api('/api/me/password', { method: 'PUT', body: JSON.stringify({ currentPassword: curPw, newPassword: newPw }) });
      setPwMsg('Password changed successfully');
      setCurPw(''); setNewPw(''); setConfPw('');
      setTimeout(() => setPwMsg(''), 3000);
    } catch (err) {
      setPwErr(err.message);
    } finally {
      setPwBusy(false);
    }
  };

  return (
    <>
      <h2>Profile</h2>
      <div className="page-sub">Manage your account details</div>
      <form className="profile-card" onSubmit={saveProfile}>
        <h3>Account Info</h3>
        <div className="field">
          <label>Username</label>
          <input value={user.username} disabled style={{opacity:0.5}} />
        </div>
        <div className="field">
          <label>Role</label>
          <input value={user.role || 'user'} disabled style={{opacity:0.5}} />
        </div>
        <div className="field">
          <label>Display Name</label>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="Your name" />
        </div>
        <div className="field">
          <label>Email</label>
          <input value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" />
        </div>
        <div className="actions">
          <button type="submit">Save Changes</button>
        </div>
        {saved && <div className="save-msg">Changes saved.</div>}
      </form>

      <form className="profile-card" onSubmit={changePassword}>
        <h3>Change Password</h3>
        {pwErr && <div className="error-banner">{pwErr}</div>}
        {pwMsg && <div className="save-msg" style={{marginBottom:12}}>{pwMsg}</div>}
        <div className="field">
          <label>Current Password</label>
          <input type="password" value={curPw} onChange={e => setCurPw(e.target.value)}
                 placeholder="••••••••" autoComplete="current-password" required />
        </div>
        <div className="field">
          <label>New Password</label>
          <input type="password" value={newPw} onChange={e => setNewPw(e.target.value)}
                 placeholder="••••••••" autoComplete="new-password" required />
        </div>
        <div className="field">
          <label>Confirm New Password</label>
          <input type="password" value={confPw} onChange={e => setConfPw(e.target.value)}
                 placeholder="••••••••" autoComplete="new-password" required />
        </div>
        <div className="actions">
          <button type="submit" disabled={pwBusy}>{pwBusy ? 'Changing...' : 'Change Password'}</button>
        </div>
      </form>
    </>
  );
}

// ── Users Page (admin only) ──────────────────────────────────────────────

function UserWebhookCreds({ user, onUpdate }) {
  const [copied, setCopied] = useState('');
  const [rotating, setRotating] = useState(false);
  const [provisioning, setProvisioning] = useState(false);
  const creds = user.webhook_creds;
  const copy = (text, key) => { navigator.clipboard.writeText(text).then(() => { setCopied(key); setTimeout(() => setCopied(''), 2000); }); };

  const rotateToken = async () => {
    if (!confirm(`Rotate the webhook auth token for "${user.username}"? The old token will stop working.`)) return;
    setRotating(true);
    try {
      await api(`/api/admin/users/${user.id}/rotate-token`, { method: 'POST' });
      onUpdate();
    } catch (err) { alert(err.message); }
    finally { setRotating(false); }
  };

  const provision = async () => {
    setProvisioning(true);
    try {
      await api(`/api/admin/users/${user.id}/rotate-token`, { method: 'POST' });
      onUpdate();
    } catch (err) { alert(err.message); }
    finally { setProvisioning(false); }
  };

  if (!creds?.provisioned) {
    const whEnabled = user.enabledServices?.includes('webhooks');
    return (
      <td colSpan={7} style={{padding:'12px 16px',background:'var(--surface-hover)'}}>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <span style={{fontSize:12,color:'var(--text-dim)'}}>
            {whEnabled ? 'Webhook credentials not yet provisioned.' : 'Enable the Webhooks service first to provision API credentials.'}
          </span>
          {whEnabled && (
            <button className="btn-sm" onClick={provision} disabled={provisioning}>
              {provisioning ? 'Provisioning...' : 'Provision Now'}
            </button>
          )}
        </div>
      </td>
    );
  }

  const authH = `-H "Authorization: Bearer ${creds.auth_token}"`;
  const ctH = `-H "Content-Type: application/json"`;
  const curlSendMsg = `curl -X POST ${creds.api_url}/api/v1/app/${creds.app_uid}/msg/ \\\n  ${authH} \\\n  ${ctH} \\\n  -d '{"eventType":"order.created","payload":{"orderId":"abc-123","amount":99.99}}'`;
  const curlAddEndpoint = `curl -X POST ${creds.api_url}/api/v1/app/${creds.app_uid}/endpoint/ \\\n  ${authH} \\\n  ${ctH} \\\n  -d '{"url":"https://your-server.com/webhook","description":"My endpoint","filterTypes":["order.created"]}'`;
  const curlAddEventType = `curl -X POST ${creds.api_url}/api/v1/event-type/ \\\n  ${authH} \\\n  ${ctH} \\\n  -d '{"name":"order.completed","description":"Triggered when an order is completed"}'`;
  const preS = {marginTop:6,background:'var(--bg)',border:'1px solid var(--border)',borderRadius:8,padding:10,fontSize:10,fontFamily:'SF Mono,Menlo,Consolas,monospace',color:'var(--text-dim)',whiteSpace:'pre-wrap',wordBreak:'break-all'};

  return (
    <td colSpan={7} style={{padding:'12px 16px',background:'var(--surface-hover)'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:10}}>
        <div style={{fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--accent)'}}>Webhook API Credentials</div>
        <button className="btn-sm btn-ghost" onClick={rotateToken} disabled={rotating} style={{fontSize:10}}>
          {rotating ? 'Rotating...' : 'Rotate Token'}
        </button>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:16}}>
        <div>
          <div style={{fontSize:10,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--text-dim)',marginBottom:4}}>API URL</div>
          <div style={{display:'flex',alignItems:'center',gap:6}}>
            <code style={{fontSize:11}}>{creds.api_url}</code>
            <button className="btn-sm btn-ghost" style={{padding:'2px 6px',fontSize:9}} onClick={() => copy(creds.api_url,'url')}>{copied==='url'?'Done':'Copy'}</button>
          </div>
        </div>
        <div>
          <div style={{fontSize:10,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--text-dim)',marginBottom:4}}>App UID</div>
          <div style={{display:'flex',alignItems:'center',gap:6}}>
            <code style={{fontSize:11}}>{creds.app_uid}</code>
            <button className="btn-sm btn-ghost" style={{padding:'2px 6px',fontSize:9}} onClick={() => copy(creds.app_uid,'uid')}>{copied==='uid'?'Done':'Copy'}</button>
          </div>
        </div>
        <div>
          <div style={{fontSize:10,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--text-dim)',marginBottom:4}}>Auth Token</div>
          <div style={{display:'flex',alignItems:'center',gap:6}}>
            <code style={{fontSize:11}}>{creds.auth_token.slice(0,24)}...</code>
            <button className="btn-sm btn-ghost" style={{padding:'2px 6px',fontSize:9}} onClick={() => copy(creds.auth_token,'token')}>{copied==='token'?'Done':'Copy'}</button>
          </div>
        </div>
      </div>
      <details style={{marginTop:10}}>
        <summary style={{cursor:'pointer',fontSize:11,color:'var(--text-dim)'}}>cURL examples</summary>
        <div style={{marginTop:6,display:'flex',flexDirection:'column',gap:8}}>
          <div><div style={{fontSize:10,fontWeight:600,color:'var(--text)',marginBottom:3}}>Send a message</div><pre style={preS}>{curlSendMsg}</pre></div>
          <div><div style={{fontSize:10,fontWeight:600,color:'var(--text)',marginBottom:3}}>Add an endpoint</div><pre style={preS}>{curlAddEndpoint}</pre></div>
          <div><div style={{fontSize:10,fontWeight:600,color:'var(--text)',marginBottom:3}}>Add an event type</div><pre style={preS}>{curlAddEventType}</pre></div>
        </div>
      </details>
    </td>
  );
}
