import React, { useCallback, useEffect, useState } from 'react';
import { AdminConsole } from './Auth.jsx';
import Netdisk from './Netdisk.jsx';
import Whiteboard from './Whiteboard.jsx';
import { api } from './api.js';

// The Quartermaster — amerc's internal management station. One panel for
// members, agents, companies & products, whiteboards, netdisk, and quick
// links to every company tool (git, docs, pm, webagent).
const LINKS = [
  { ico: '🗡️', label: 'Git', sub: 'source · Gitea', href: 'https://git.amerc.ai/' },
  { ico: '📄', label: 'Docs', sub: 'guides + API reference', href: 'https://docs.amerc.ai/' },
  { ico: '🧠', label: 'PM workspace', sub: 'standalone pm.amerc.ai', href: 'https://pm.amerc.ai/' },
  { ico: '🤖', label: 'Webagent', sub: 'relay health', href: 'https://webagent.amerc.ai/health' },
  { ico: '🏰', label: 'Tavern', sub: 'the public site', href: 'https://amerc.ai/' },
];

function Boards() {
  const [boards, setBoards] = useState([]);
  const [open, setOpen] = useState(null);
  const [err, setErr] = useState('');
  const load = useCallback(async () => { try { const d = await api('/boards'); setBoards(d.boards || []); } catch (e) { setErr(e.message); } }, []);
  useEffect(() => { load(); }, [load]);
  const create = async () => {
    const name = window.prompt('Whiteboard name', 'New mindmap'); if (!name) return;
    try { const r = await api('/boards', { method: 'POST', body: { name, data: JSON.stringify({ nodes: [], edges: [] }) } }); await load(); setOpen(r.id); } catch (e) { setErr(e.message); }
  };
  const del = async (id) => { if (!window.confirm('Delete board?')) return; try { await api(`/boards/${id}`, { method: 'DELETE' }); load(); } catch (e) { setErr(e.message); } };
  if (open) return <Whiteboard boardId={open} onClose={() => { setOpen(null); load(); }} />;
  return (
    <div className="pm-cards">
      <div className="pm-cards-head"><h2>Whiteboards</h2><button className="cs-btn cs-primary" onClick={create}>+ New mindmap</button></div>
      {err && <p className="cs-err">{err}</p>}
      <div className="pm-grid">
        {boards.map((b) => (
          <div key={b.id} className="pm-card" onClick={() => setOpen(b.id)}>
            <div className="pm-card-ico">🧠</div>
            <strong>{b.name}</strong>
            <span>{(JSON.parse(b.links || '[]') || []).length} linked files</span>
            <small>updated {new Date(b.updated_at).toLocaleString()} · {b.updated_by}</small>
            <button className="pm-card-del" onClick={(e) => { e.stopPropagation(); del(b.id); }}>✕</button>
          </div>
        ))}
        {!boards.length && <p className="cs-hint">No whiteboards yet. Create a mindmap and link netdisk files to its nodes.</p>}
      </div>
    </div>
  );
}

function CommandPost() {
  const [stats, setStats] = useState(null);
  const [members, setMembers] = useState(null);
  useEffect(() => {
    api('/agents/stats').then(setStats).catch(() => {});
    api('/admin/users').then((d) => setMembers((d.users || []).length)).catch(() => {});
  }, []);
  const S = [
    ['members', members], ['agent classes', stats?.classes], ['online now', stats?.online], ['live sessions', stats?.sessions],
  ];
  return (
    <div className="qm-post">
      <div className="qm-stats">
        {S.map(([label, v]) => <div key={label} className="qm-stat"><b>{v ?? '·'}</b><span>{label}</span></div>)}
      </div>
      <h4 className="ap-h4">Company tools</h4>
      <div className="qm-links">
        {LINKS.map((l) => (
          <a key={l.label} className="qm-link" href={l.href} target="_blank" rel="noreferrer">
            <span className="qm-link-ico" aria-hidden="true">{l.ico}</span>
            <div className="qm-link-t"><strong>{l.label}</strong><span>{l.sub}</span></div>
            <span className="qm-link-go" aria-hidden="true">↗</span>
          </a>
        ))}
      </div>
    </div>
  );
}

const QTABS = [
  { key: 'post', label: '⚜ Command post' },
  { key: 'ops', label: '🛡 Tenants · keys · company' },
  { key: 'boards', label: '🧠 Whiteboards' },
  { key: 'disk', label: '🗄 Netdisk' },
];

export default function Quartermaster({ auth }) {
  const [tab, setTab] = useState('post');
  if (!auth.ready) return <div className="ap"><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>;
  return (
    <div className="qm">
      <div className="qm-head">
        <span className="qm-tag">⚜ QUARTERMASTER</span>
        <h2>amerc command post</h2>
        <p>The company's internal station — members, agents, companies &amp; products, whiteboards, netdisk, and every tool in one place.</p>
      </div>
      <div className="qm-tabs">
        {QTABS.map((t) => <button key={t.key} className={tab === t.key ? 'on' : ''} onClick={() => setTab(t.key)} type="button">{t.label}</button>)}
      </div>
      <div className="qm-body">
        {tab === 'post' && <CommandPost />}
        {tab === 'ops' && <AdminConsole auth={auth} />}
        {tab === 'boards' && <Boards />}
        {tab === 'disk' && <div className="pm-disk"><h2>Netdisk</h2><Netdisk /></div>}
      </div>
    </div>
  );
}
