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

function BoardsTab() {
  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 PortfolioTab() {
  const [companies, setCompanies] = useState([]);
  const [products, setProducts] = useState([]);
  const [err, setErr] = useState('');
  useEffect(() => {
    Promise.allSettled([api('/admin/companies'), api('/admin/products')]).then(([c, p]) => {
      if (c.status === 'fulfilled') setCompanies(c.value.companies || []);
      if (p.status === 'fulfilled') setProducts(p.value.products || []);
      if (c.status === 'rejected') setErr('Portfolio is admin-only. Ask an admin for access.');
    });
  }, []);
  return (
    <div className="pm-portfolio">
      <h2>Portfolio</h2>
      {err && <p className="cs-hint">{err}</p>}
      <div className="pm-port-cols">
        <div><h3>Companies</h3>{companies.map((c) => <div key={c.id} className="pm-port-row"><strong>{c.name}</strong><span>{c.tier}</span><em className={`risk-${c.risk}`}>{c.risk}</em></div>)}{!companies.length && <p className="cs-hint">—</p>}</div>
        <div><h3>Products</h3>{products.map((p) => <div key={p.id} className="pm-port-row"><strong>{p.name}</strong><span>{p.status}</span><em>{p.price}</em></div>)}{!products.length && <p className="cs-hint">—</p>}</div>
      </div>
    </div>
  );
}

const TABS = [
  { key: 'boards', label: 'Whiteboards', el: <BoardsTab /> },
  { key: 'disk', label: 'Netdisk', el: <div className="pm-disk"><h2>Netdisk</h2><Netdisk /></div> },
  { key: 'portfolio', label: 'Portfolio', el: <PortfolioTab /> },
];

function PmWorkspace() {
  const [tab, setTab] = useState('boards');
  return (
    <div className="pm">
      <nav className="pm-nav">
        {TABS.map((t) => <button key={t.key} className={tab === t.key ? 'on' : ''} onClick={() => setTab(t.key)}>{t.label}</button>)}
        <a className="pm-nav-ext" href="https://docs.amerc.ai/">Docs ↗</a>
      </nav>
      <div className="pm-body">{TABS.find((t) => t.key === tab)?.el}</div>
    </div>
  );
}

export default function PmApp() {
  return <ConsoleShell title="pm" accent="#36f0b0" current="pm" requireRole="admin">{() => <PmWorkspace />}</ConsoleShell>;
}
