import React, { useCallback, useEffect, useState } from 'react';
import { api } from './api.js';

// Session hook --------------------------------------------------------------
export function useAuth() {
  const [user, setUser] = useState(null);
  const [ready, setReady] = useState(false);
  const refresh = useCallback(async () => {
    try { const d = await api('/auth/me'); setUser(d.user || null); }
    catch { setUser(null); }
    finally { setReady(true); }
  }, []);
  useEffect(() => { refresh(); }, [refresh]);
  const logout = useCallback(async () => { try { await api('/auth/logout', { method: 'POST' }); } catch {} setUser(null); }, []);
  return { user, ready, setUser, refresh, logout };
}

// Login / Signup ------------------------------------------------------------
export function AuthPanel({ auth, onDone }) {
  const [mode, setMode] = useState('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [handle, setHandle] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  if (auth.user) return <SignedInPanel auth={auth} />;

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const path = mode === 'login' ? '/auth/login' : '/auth/signup';
      const d = await api(path, { method: 'POST', body: { email, password, handle } });
      auth.setUser(d.user);
      onDone && onDone(d.user);
    } catch (e2) { setErr(e2.message); }
    finally { setBusy(false); }
  };

  return (
    <form className="px-auth" onSubmit={submit}>
      <div className="px-auth-tabs">
        <button type="button" className={mode === 'login' ? 'active' : ''} onClick={() => setMode('login')}>Login</button>
        <button type="button" className={mode === 'signup' ? 'active' : ''} onClick={() => setMode('signup')}>Sign Up</button>
      </div>
      <label className="px-field"><span>Guild handle email</span>
        <input type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="operator@vertical-site.ai" required />
      </label>
      {mode === 'signup' && (
        <label className="px-field"><span>Display name</span>
          <input value={handle} onChange={(e) => setHandle(e.target.value)} placeholder="ironworks" />
        </label>
      )}
      <label className="px-field"><span>Access sigil</span>
        <input type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} value={password} onChange={(e) => setPassword(e.target.value)} placeholder="min 6 chars" required minLength={6} />
      </label>
      {err && <p className="px-auth-err">{err}</p>}
      <button type="submit" className="px-action px-auth-submit" disabled={busy}>
        {busy ? '…' : mode === 'login' ? 'Enter Booth' : 'Create Account'}
      </button>
      <p className="px-auth-hint">{mode === 'login' ? 'New mercenary? Switch to Sign Up.' : 'The first account becomes Quartermaster (admin).'}</p>
    </form>
  );
}

function SignedInPanel({ auth }) {
  const [pw, setPw] = useState(false);
  const [cur, setCur] = useState('');
  const [nw, setNw] = useState('');
  const [msg, setMsg] = useState('');
  const [err, setErr] = useState('');
  const change = async (e) => {
    e.preventDefault(); setErr(''); setMsg('');
    try { await api('/auth/password', { method: 'POST', body: { currentPassword: cur, newPassword: nw } }); setMsg('Password updated.'); setCur(''); setNw(''); setPw(false); }
    catch (e2) { setErr(e2.message); }
  };
  return (
    <div className="px-auth">
      <p className="px-auth-hi">Signed in as <strong>{auth.user.handle}</strong> <em>({auth.user.role})</em></p>
      {msg && <p className="px-auth-hint" style={{ color: '#36f0b0' }}>{msg}</p>}
      <div className="px-auth-actions">
        {auth.user.role === 'admin' && <button type="button" className="px-action" onClick={() => { window.location.hash = '#/admin'; }}>Quartermaster</button>}
        <a className="px-action" href={`https://pm.amerc.ai/`}>PM Site</a>
        <a className="px-action" href={`https://docs.amerc.ai/`}>Docs</a>
        <button type="button" className="px-action" onClick={() => setPw((v) => !v)}>Change Password</button>
        <button type="button" className="px-action" onClick={() => auth.logout()}>Log Out</button>
      </div>
      {pw && (
        <form className="px-auth" onSubmit={change} style={{ marginTop: 8 }}>
          <label className="px-field"><span>Current password</span>
            <input type="password" value={cur} onChange={(e) => setCur(e.target.value)} required /></label>
          <label className="px-field"><span>New password (min 6)</span>
            <input type="password" value={nw} onChange={(e) => setNw(e.target.value)} required minLength={6} /></label>
          {err && <p className="px-auth-err">{err}</p>}
          <button type="submit" className="px-action px-auth-submit">Update Password</button>
        </form>
      )}
    </div>
  );
}

// Admin console (Quartermaster backdoor) ------------------------------------
const TABS = [
  { key: 'users', label: 'Users', cols: ['handle', 'email', 'role', 'status'] },
  { key: 'companies', label: 'Companies', cols: ['name', 'tier', 'risk', 'notes'] },
  { key: 'products', label: 'Products', cols: ['name', 'company_id', 'status', 'price', 'notes'] },
  { key: 'keys', label: 'Agent Keys', cols: ['name', 'prefix', 'last_used'] },
];

export function AdminConsole({ auth }) {
  const [tab, setTab] = useState('users');
  const [rows, setRows] = useState([]);
  const [err, setErr] = useState('');
  const [draft, setDraft] = useState({});

  const load = useCallback(async (key) => {
    setErr('');
    try { const d = await api(`/admin/${key}`); setRows(d[key] || []); }
    catch (e) { setErr(e.message); setRows([]); }
  }, []);
  useEffect(() => { if (auth.user?.role === 'admin') load(tab); }, [tab, auth.user, load]);

  if (!auth.ready) return <div className="px-admin"><p>Loading…</p></div>;
  if (!auth.user) {
    return (
      <div className="px-admin px-admin-gate">
        <h3>Backdoor sealed</h3>
        <p>Quartermaster credentials required.</p>
        <button className="px-action" onClick={() => { window.location.hash = '#/signin'; }}>Go to Login</button>
      </div>
    );
  }
  if (auth.user.role !== 'admin') {
    return <div className="px-admin px-admin-gate"><h3>Not authorised</h3><p>{auth.user.handle} is a member, not Quartermaster.</p></div>;
  }

  const meta = TABS.find((t) => t.key === tab);
  const editable = meta.cols.filter((c) => tab !== 'users' || true);

  const create = async () => {
    try {
      const r = await api(`/admin/${tab}`, { method: 'POST', body: draft });
      if (tab === 'keys' && r.key) window.alert(`Agent key (copy now, shown once):\n\n${r.key}`);
      setDraft({}); load(tab);
    } catch (e) { setErr(e.message); }
  };
  const patch = async (id, patchBody) => {
    try { await api(`/admin/${tab}/${id}`, { method: 'PATCH', body: patchBody }); load(tab); }
    catch (e) { setErr(e.message); }
  };
  const del = async (id) => {
    if (!window.confirm('Delete this record?')) return;
    try { await api(`/admin/${tab}/${id}`, { method: 'DELETE' }); load(tab); }
    catch (e) { setErr(e.message); }
  };

  return (
    <div className="px-admin">
      <div className="px-admin-tabs">
        {TABS.map((t) => (
          <button key={t.key} className={tab === t.key ? 'active' : ''} onClick={() => setTab(t.key)} type="button">{t.label}</button>
        ))}
        <span className="px-admin-who">{auth.user.handle} · admin</span>
      </div>
      {err && <p className="px-auth-err">{err}</p>}
      <div className="px-admin-table">
        <div className="px-admin-row px-admin-head">
          {meta.cols.map((c) => <span key={c}>{c}</span>)}
          <span>actions</span>
        </div>
        {rows.map((r) => (
          <div className="px-admin-row" key={r.id}>
            {meta.cols.map((c) => {
              if (tab === 'users' && c === 'role') return (
                <select key={c} value={r.role} onChange={(e) => patch(r.id, { role: e.target.value })}>
                  <option value="member">member</option><option value="admin">admin</option>
                </select>);
              if (tab === 'users' && c === 'status') return (
                <select key={c} value={r.status} onChange={(e) => patch(r.id, { status: e.target.value })}>
                  <option value="active">active</option><option value="suspended">suspended</option>
                </select>);
              return <span key={c} title={String(r[c] ?? '')}>{String(r[c] ?? '')}</span>;
            })}
            <span className="px-admin-acts"><button type="button" onClick={() => del(r.id)}>✕</button></span>
          </div>
        ))}
        {!rows.length && <div className="px-admin-row px-admin-empty">no records</div>}
      </div>
      {tab !== 'users' && (
        <div className="px-admin-new">
          {(tab === 'keys' ? ['name'] : editable).map((c) => (
            <input key={c} placeholder={tab === 'keys' ? 'agent key name' : c} value={draft[c] ?? ''} onChange={(e) => setDraft((d) => ({ ...d, [c]: e.target.value }))} />
          ))}
          <button type="button" className="px-action" onClick={create}>{tab === 'keys' ? '+ Mint Key' : '+ Add'}</button>
        </div>
      )}
    </div>
  );
}
