// ── Disposable Mail Admin ─────────────────────────────────────────────

function MailAdminPage() {
  const [tab, setTab] = useState('keys');
  const [apiKeys, setApiKeys] = useState([]);
  const [ttlConfigs, setTtlConfigs] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [showTtlCreate, setShowTtlCreate] = useState(false);
  const [usageKeyId, setUsageKeyId] = useState(null);
  const [usageLogs, setUsageLogs] = useState([]);
  const [usageTotal, setUsageTotal] = useState(0);
  const [copied, setCopied] = useState('');

  const loadKeys = useCallback(() => {
    api('/api/admin/mail/api-keys').then(setApiKeys).catch(e => setError(e.message));
  }, []);

  const loadTtls = useCallback(() => {
    api('/api/admin/mail/ttl-configs').then(setTtlConfigs).catch(e => setError(e.message));
  }, []);

  const loadStats = useCallback(() => {
    api('/api/admin/mail/stats').then(setStats).catch(() => {});
  }, []);

  useEffect(() => {
    setLoading(true);
    Promise.all([
      api('/api/admin/mail/api-keys'),
      api('/api/admin/mail/ttl-configs'),
      api('/api/admin/mail/stats'),
    ]).then(([k, t, s]) => {
      setApiKeys(k); setTtlConfigs(t); setStats(s); setError('');
    }).catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const loadUsage = async (keyId) => {
    if (usageKeyId === keyId) { setUsageKeyId(null); return; }
    try {
      const data = await api(`/api/admin/mail/api-keys/${keyId}/usage?limit=50`);
      setUsageLogs(data.logs); setUsageTotal(data.total); setUsageKeyId(keyId);
    } catch (e) { setError(e.message); }
  };

  const copy = (text, id) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(id); setTimeout(() => setCopied(''), 2000);
    });
  };

  const toggleKeyActive = async (id, active) => {
    try {
      await api(`/api/admin/mail/api-keys/${id}`, {
        method: 'PUT', body: JSON.stringify({ active: !active }),
      });
      loadKeys();
    } catch (e) { setError(e.message); }
  };

  const deleteKey = async (id, label) => {
    if (!confirm(`Revoke API key "${label || id}"? This cannot be undone.`)) return;
    try {
      await api(`/api/admin/mail/api-keys/${id}`, { method: 'DELETE' });
      if (usageKeyId === id) setUsageKeyId(null);
      loadKeys(); loadStats();
    } catch (e) { setError(e.message); }
  };

  const deleteTtl = async (id) => {
    if (!confirm('Delete this TTL override?')) return;
    try {
      await api(`/api/admin/mail/ttl-configs/${id}`, { method: 'DELETE' });
      loadTtls(); loadStats();
    } catch (e) { setError(e.message); }
  };

  const tabStyle = (t) => ({
    padding: '8px 16px', cursor: 'pointer', fontWeight: 600, fontSize: 13,
    borderBottom: tab === t ? '2px solid var(--accent)' : '2px solid transparent',
    color: tab === t ? 'var(--accent)' : 'var(--text-dim)',
    background: 'none', border: 'none', borderBottomStyle: 'solid',
  });

  if (loading) return (<><h2>Disposable Mail</h2><div className="wh-empty"><p>Loading...</p></div></>);

  return (
    <>
      <h2>Disposable Mail</h2>
      <div className="page-sub">Manage B2B API keys, email TTL overrides, and monitor usage</div>

      {stats && (
        <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:20}}>
          {[
            { label: 'Emails in DB', value: stats.emails },
            { label: 'API Keys', value: `${stats.apiKeys.active} active / ${stats.apiKeys.total} total` },
            { label: 'TTL Overrides', value: stats.ttlConfigs },
            { label: 'API Calls (24h)', value: stats.apiRequests24h },
          ].map(s => (
            <div key={s.label} className="card" style={{padding:'14px 16px'}}>
              <div style={{fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--text-dim)',marginBottom:4}}>{s.label}</div>
              <div style={{fontSize:20,fontWeight:700,color:'var(--text)'}}>{s.value}</div>
            </div>
          ))}
        </div>
      )}

      {error && <div className="error-banner">{error}</div>}

      <div style={{display:'flex',gap:0,borderBottom:'1px solid var(--border)',marginBottom:16}}>
        <button style={tabStyle('keys')} onClick={() => setTab('keys')}>API Keys</button>
        <button style={tabStyle('ttl')} onClick={() => setTab('ttl')}>TTL Overrides</button>
      </div>

      {tab === 'keys' && (
        <>
          <div className="wh-toolbar">
            <h3>{apiKeys.length} API key{apiKeys.length !== 1 ? 's' : ''}</h3>
            <button className="btn-sm" onClick={() => setShowCreate(!showCreate)}>
              {showCreate ? 'Cancel' : '+ Create Key'}
            </button>
          </div>

          {showCreate && <CreateApiKeyForm onCreated={() => { setShowCreate(false); loadKeys(); loadStats(); }} />}

          {apiKeys.length === 0 ? (
            <div className="wh-empty"><p>No API keys yet. Create one to get started.</p></div>
          ) : (
            <table className="wh-table">
              <thead>
                <tr>
                  <th>Label</th>
                  <th>Key</th>
                  <th>Status</th>
                  <th>Requests</th>
                  <th>Last Used</th>
                  <th>Created</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {apiKeys.map(k => (
                  <React.Fragment key={k.id}>
                    <tr style={{opacity: k.active ? 1 : 0.5}}>
                      <td style={{fontWeight:600}}>{k.label || '—'}</td>
                      <td>
                        <div style={{display:'flex',alignItems:'center',gap:6}}>
                          <code style={{fontSize:11,fontFamily:'SF Mono,Menlo,Consolas,monospace',color:'var(--text-dim)'}}>{k.key.slice(0,20)}...</code>
                          <button className="btn-sm btn-ghost" style={{padding:'2px 6px',fontSize:9}}
                                  onClick={() => copy(k.key, `key-${k.id}`)}>
                            {copied === `key-${k.id}` ? 'Done' : 'Copy'}
                          </button>
                        </div>
                      </td>
                      <td>
                        <span className={`badge badge-${k.active ? 'active' : 'planned'}`}>
                          {k.active ? 'active' : 'disabled'}
                        </span>
                      </td>
                      <td style={{fontFamily:'SF Mono,Menlo,Consolas,monospace',fontSize:12}}>{k.total_requests.toLocaleString()}</td>
                      <td style={{color:'var(--text-dim)',fontSize:12}}>
                        {k.last_used_at ? new Date(k.last_used_at).toLocaleString() : 'never'}
                      </td>
                      <td style={{color:'var(--text-dim)',fontSize:12}}>
                        {new Date(k.created_at).toLocaleDateString()}
                      </td>
                      <td>
                        <div style={{display:'flex',gap:6}}>
                          <button className="btn-sm btn-ghost" onClick={() => loadUsage(k.id)}
                                  style={{color: usageKeyId === k.id ? 'var(--accent)' : undefined}}>
                            {usageKeyId === k.id ? 'Hide' : 'Usage'}
                          </button>
                          <button className="btn-sm btn-ghost" onClick={() => toggleKeyActive(k.id, k.active)}>
                            {k.active ? 'Disable' : 'Enable'}
                          </button>
                          <button className="btn-sm btn-danger" onClick={() => deleteKey(k.id, k.label)}>Revoke</button>
                        </div>
                      </td>
                    </tr>
                    {usageKeyId === k.id && (
                      <tr>
                        <td colSpan={7} style={{padding:'12px 16px',background:'var(--surface-hover)'}}>
                          <div style={{fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.05em',color:'var(--accent)',marginBottom:8}}>
                            Recent Usage ({usageTotal} total requests)
                          </div>
                          {usageLogs.length === 0 ? (
                            <div style={{fontSize:12,color:'var(--text-dim)'}}>No usage recorded yet.</div>
                          ) : (
                            <div style={{maxHeight:240,overflowY:'auto'}}>
                              <table style={{width:'100%',fontSize:11,borderCollapse:'collapse'}}>
                                <thead>
                                  <tr style={{borderBottom:'1px solid var(--border)'}}>
                                    <th style={{textAlign:'left',padding:'4px 8px',color:'var(--text-dim)'}}>Time</th>
                                    <th style={{textAlign:'left',padding:'4px 8px',color:'var(--text-dim)'}}>Method</th>
                                    <th style={{textAlign:'left',padding:'4px 8px',color:'var(--text-dim)'}}>Path</th>
                                    <th style={{textAlign:'left',padding:'4px 8px',color:'var(--text-dim)'}}>Status</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {usageLogs.map(l => (
                                    <tr key={l.id} style={{borderBottom:'1px solid var(--border)'}}>
                                      <td style={{padding:'4px 8px',color:'var(--text-dim)',fontFamily:'SF Mono,Menlo,Consolas,monospace'}}>
                                        {new Date(l.ts).toLocaleString()}
                                      </td>
                                      <td style={{padding:'4px 8px',fontWeight:600}}>{l.method}</td>
                                      <td style={{padding:'4px 8px',fontFamily:'SF Mono,Menlo,Consolas,monospace',color:'var(--text-dim)'}}>{l.path}</td>
                                      <td style={{padding:'4px 8px'}}>
                                        <span style={{color: l.status_code < 400 ? 'var(--green)' : 'var(--red)'}}>{l.status_code}</span>
                                      </td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </div>
                          )}
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          )}
        </>
      )}

      {tab === 'ttl' && (
        <>
          <div className="wh-toolbar">
            <h3>{ttlConfigs.length} TTL override{ttlConfigs.length !== 1 ? 's' : ''}</h3>
            <button className="btn-sm" onClick={() => setShowTtlCreate(!showTtlCreate)}>
              {showTtlCreate ? 'Cancel' : '+ Add Override'}
            </button>
          </div>

          {showTtlCreate && <CreateTtlForm onCreated={() => { setShowTtlCreate(false); loadTtls(); loadStats(); }} />}

          <div className="card" style={{padding:'12px 16px',marginBottom:16,fontSize:12,color:'var(--text-dim)'}}>
            Default TTL is <strong style={{color:'var(--text)'}}>36 hours</strong>. Add overrides to keep emails longer for specific address patterns.
            Use exact addresses like <code>qa-bot@mail.vibey.cloud</code> or LIKE patterns like <code>qa-%@mail.vibey.cloud</code>.
          </div>

          {ttlConfigs.length === 0 ? (
            <div className="wh-empty"><p>No TTL overrides. All emails expire after 36 hours.</p></div>
          ) : (
            <table className="wh-table">
              <thead>
                <tr>
                  <th>Address Pattern</th>
                  <th>TTL</th>
                  <th>Created By</th>
                  <th>Created</th>
                  <th>Expires</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {ttlConfigs.map(t => (
                  <tr key={t.id}>
                    <td><code style={{fontSize:12,fontFamily:'SF Mono,Menlo,Consolas,monospace'}}>{t.address_pattern}</code></td>
                    <td style={{fontWeight:600}}>{t.ttl_hours}h {t.ttl_hours >= 24 && <span style={{color:'var(--text-dim)',fontWeight:400,fontSize:11}}>({Math.round(t.ttl_hours/24)}d)</span>}</td>
                    <td style={{color:'var(--text-dim)',fontSize:12}}>{t.created_by}</td>
                    <td style={{color:'var(--text-dim)',fontSize:12}}>{new Date(t.created_at).toLocaleDateString()}</td>
                    <td style={{color:'var(--text-dim)',fontSize:12}}>{t.expires_at ? new Date(t.expires_at).toLocaleDateString() : 'never'}</td>
                    <td>
                      <button className="btn-sm btn-danger" onClick={() => deleteTtl(t.id)}>Delete</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </>
      )}
    </>
  );
}

function CreateApiKeyForm({ onCreated }) {
  const [label, setLabel] = useState('');
  const [saving, setSaving] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true); setError('');
    try {
      const data = await api('/api/admin/mail/api-keys', {
        method: 'POST', body: JSON.stringify({ label }),
      });
      setResult(data);
    } catch (err) { setError(err.message); }
    finally { setSaving(false); }
  };

  if (result) {
    return (
      <div className="wh-form" style={{borderColor:'var(--green)'}}>
        <div style={{fontWeight:600,color:'var(--green)',marginBottom:8}}>API Key Created</div>
        <p style={{fontSize:12,color:'var(--text-dim)',marginBottom:8}}>
          Copy this key now — it won't be shown in full again.
        </p>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <code style={{fontSize:12,fontFamily:'SF Mono,Menlo,Consolas,monospace',padding:'6px 10px',background:'var(--bg)',border:'1px solid var(--border)',borderRadius:6,flex:1,wordBreak:'break-all'}}>
            {result.key}
          </code>
          <button className="btn-sm" onClick={() => {
            navigator.clipboard.writeText(result.key);
            setCopied(true); setTimeout(() => setCopied(false), 2000);
          }}>{copied ? 'Copied!' : 'Copy'}</button>
        </div>
        <button className="btn-sm btn-ghost" style={{marginTop:12}} onClick={onCreated}>Done</button>
      </div>
    );
  }

  return (
    <form className="wh-form" onSubmit={submit}>
      {error && <div className="error-banner">{error}</div>}
      <div className="field">
        <label>Label (what this key is for)</label>
        <input value={label} onChange={e => setLabel(e.target.value)}
               placeholder="e.g. QA Automation, CI Pipeline" required />
      </div>
      <button type="submit" disabled={saving}>{saving ? 'Creating...' : 'Create API Key'}</button>
    </form>
  );
}

function CreateTtlForm({ onCreated }) {
  const [pattern, setPattern] = useState('');
  const [hours, setHours] = useState('168');
  const [expiresAt, setExpiresAt] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true); setError('');
    try {
      await api('/api/admin/mail/ttl-configs', {
        method: 'POST',
        body: JSON.stringify({
          addressPattern: pattern,
          ttlHours: parseInt(hours, 10),
          expiresAt: expiresAt || undefined,
        }),
      });
      onCreated();
    } catch (err) { setError(err.message); }
    finally { setSaving(false); }
  };

  return (
    <form className="wh-form" onSubmit={submit}>
      {error && <div className="error-banner">{error}</div>}
      <div style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr',gap:12}}>
        <div className="field">
          <label>Address Pattern</label>
          <input value={pattern} onChange={e => setPattern(e.target.value)}
                 placeholder="qa-%@mail.vibey.cloud" required />
        </div>
        <div className="field">
          <label>TTL (hours)</label>
          <input type="number" min="1" max="8760" value={hours}
                 onChange={e => setHours(e.target.value)} required />
          <div style={{fontSize:10,color:'var(--text-dim)',marginTop:2}}>
            {parseInt(hours) >= 24 ? `${Math.round(parseInt(hours)/24)} days` : `${hours} hours`}
          </div>
        </div>
        <div className="field">
          <label>Config Expires (optional)</label>
          <input type="date" value={expiresAt} onChange={e => setExpiresAt(e.target.value)} />
        </div>
      </div>
      <button type="submit" disabled={saving}>{saving ? 'Creating...' : 'Add TTL Override'}</button>
    </form>
  );
}
