'use client';

import { useEffect, useState } from 'react';

const BANNER_STYLES = {
  red: { background: '#3a0d0d', color: '#ffb4b4', border: '1px solid #7a1c1c' },
  amber: { background: '#3a2a0d', color: '#ffd6a0', border: '1px solid #7a5a1c' },
  grey: { background: '#202225', color: '#b8b8b8', border: '1px solid #3a3a3a' },
};

const ALLOWED_MODES = ['strict', 'balanced', 'permissive'];

export default function PrintingPressPanel() {
  const [snapshot, setSnapshot] = useState(null);
  const [clis, setClis] = useState([]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);
  const [installSlug, setInstallSlug] = useState('');
  const [installSource, setInstallSource] = useState('starter-pack');
  const [installSourceUrl, setInstallSourceUrl] = useState('');

  async function refresh() {
    try {
      const [secRes, clisRes] = await Promise.all([
        fetch('/api/printing-press/security-mode'),
        fetch('/api/printing-press/clis'),
      ]);
      const sec = await secRes.json();
      const cs = await clisRes.json();
      if (sec?.ok) setSnapshot(sec);
      if (cs?.ok) setClis(cs.clis || []);
    } catch (err) {
      setError(err?.message || String(err));
    }
  }

  useEffect(() => { refresh(); }, []);

  async function flipMode(nextMode) {
    setError(null);
    if (!confirm(`Flip Printing Press security mode to "${nextMode}"? This is audited.`)) return;
    setBusy(true);
    try {
      const res = await fetch('/api/printing-press/security-mode', {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ mode: nextMode, confirm: true, reason: 'UI flip' }),
      });
      const data = await res.json();
      if (!data?.ok) setError(data?.error || 'flip failed');
      await refresh();
    } catch (err) {
      setError(err?.message || String(err));
    } finally {
      setBusy(false);
    }
  }

  async function installStarterPack() {
    setError(null);
    setBusy(true);
    try {
      const res = await fetch('/api/printing-press/install', { method: 'POST' });
      const data = await res.json();
      if (data?.status === 'approval_required') {
        setError(`Approval required (id: ${data.approval_request_id}). Approve in /approvals.`);
      } else if (!data?.ok) {
        setError(data?.reason || data?.error || `install ${data?.status || 'failed'}`);
      }
      await refresh();
    } catch (err) {
      setError(err?.message || String(err));
    } finally {
      setBusy(false);
    }
  }

  async function generateCli(e) {
    e?.preventDefault?.();
    setError(null);
    if (!installSlug) return setError('slug required');
    setBusy(true);
    try {
      const res = await fetch('/api/printing-press/clis', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ slug: installSlug, source: installSource, source_url: installSourceUrl || null }),
      });
      const data = await res.json();
      if (data?.status === 'approval_required') {
        setError(`Approval required (id: ${data.approval_request_id}).`);
      } else if (!data?.ok) {
        setError(data?.reason || data?.error || `generate ${data?.status || 'failed'}`);
      } else {
        setInstallSlug('');
        setInstallSourceUrl('');
      }
      await refresh();
    } catch (err) {
      setError(err?.message || String(err));
    } finally {
      setBusy(false);
    }
  }

  if (!snapshot) {
    return <div style={{ padding: 16, color: '#aaa' }}>Loading Printing Press…</div>;
  }

  const caps = snapshot.capabilities || {};
  const banner = BANNER_STYLES[caps.banner] || BANNER_STYLES.grey;

  return (
    <section style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <header>
        <h2 style={{ margin: 0, fontSize: 18, letterSpacing: '-0.01em' }}>Printing Press</h2>
        <p style={{ margin: '4px 0 0', color: '#888', fontSize: 13 }}>
          Agent-native CLI generator. Generates Go binaries, Claude Code skills, MCP servers, and local SQLite mirrors.
        </p>
      </header>

      <div style={{ ...banner, padding: '10px 14px', borderRadius: 8, fontSize: 13 }}>
        <strong style={{ textTransform: 'uppercase', letterSpacing: 0.5 }}>
          Security mode: {snapshot.mode}
        </strong>
        <div style={{ marginTop: 4 }}>{caps.banner_message}</div>
        <div style={{ marginTop: 6, fontSize: 12, opacity: 0.85 }}>
          force_approval: {String(caps.force_approval)} · allow_mcp_mount: {String(caps.allow_mcp_mount)} ·
          rate × {caps.rate_limit_multiplier} · production_safe: {String(caps.production_safe)}
        </div>
        <div style={{ marginTop: 10, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {ALLOWED_MODES.map((m) => (
            <button
              key={m}
              type="button"
              disabled={busy || m === snapshot.mode}
              onClick={() => flipMode(m)}
              style={{
                padding: '4px 10px',
                fontSize: 12,
                borderRadius: 4,
                border: m === snapshot.mode ? '1px solid #fff' : '1px solid #555',
                background: m === snapshot.mode ? '#fff' : 'transparent',
                color: m === snapshot.mode ? '#000' : '#ddd',
                cursor: m === snapshot.mode ? 'default' : 'pointer',
              }}
            >
              {m}
            </button>
          ))}
        </div>
      </div>

      {error && (
        <div style={{ padding: 10, background: '#3a1010', color: '#ffb4b4', borderRadius: 6, fontSize: 13 }}>
          {error}
        </div>
      )}

      <div>
        <button
          type="button"
          disabled={busy}
          onClick={installStarterPack}
          style={{ padding: '8px 14px', fontSize: 13, borderRadius: 6, border: '1px solid #555', background: '#1a1a1a', color: '#eee', cursor: 'pointer' }}
        >
          Install starter pack
        </button>
        <span style={{ marginLeft: 12, color: '#888', fontSize: 12 }}>
          Always approval-gated (irreversible_external).
        </span>
      </div>

      <form onSubmit={generateCli} style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'flex-end' }}>
        <label style={{ display: 'flex', flexDirection: 'column', fontSize: 12, color: '#aaa' }}>
          slug
          <input
            value={installSlug}
            onChange={(e) => setInstallSlug(e.target.value)}
            placeholder="hacker-news"
            style={{ padding: '6px 8px', background: '#0d0d0d', border: '1px solid #333', color: '#eee', borderRadius: 4, fontSize: 13 }}
          />
        </label>
        <label style={{ display: 'flex', flexDirection: 'column', fontSize: 12, color: '#aaa' }}>
          source
          <select
            value={installSource}
            onChange={(e) => setInstallSource(e.target.value)}
            style={{ padding: '6px 8px', background: '#0d0d0d', border: '1px solid #333', color: '#eee', borderRadius: 4, fontSize: 13 }}
          >
            <option value="starter-pack">starter-pack</option>
            <option value="github">github</option>
            <option value="local">local</option>
            <option value="spec">spec</option>
          </select>
        </label>
        {installSource !== 'starter-pack' && (
          <label style={{ display: 'flex', flexDirection: 'column', fontSize: 12, color: '#aaa', flex: 1, minWidth: 200 }}>
            source_url
            <input
              value={installSourceUrl}
              onChange={(e) => setInstallSourceUrl(e.target.value)}
              placeholder={installSource === 'github' ? 'org/repo' : installSource === 'local' ? '/abs/path' : 'https://…openapi.yaml'}
              style={{ padding: '6px 8px', background: '#0d0d0d', border: '1px solid #333', color: '#eee', borderRadius: 4, fontSize: 13 }}
            />
          </label>
        )}
        <button
          type="submit"
          disabled={busy || !installSlug}
          style={{ padding: '7px 14px', fontSize: 13, borderRadius: 4, border: '1px solid #555', background: '#1a1a1a', color: '#eee', cursor: 'pointer' }}
        >
          Generate CLI
        </button>
      </form>

      <div>
        <h3 style={{ margin: '0 0 8px', fontSize: 14, color: '#ddd' }}>Installed CLIs ({clis.length})</h3>
        {clis.length === 0 ? (
          <div style={{ color: '#666', fontSize: 13 }}>No CLIs installed.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ textAlign: 'left', color: '#888', borderBottom: '1px solid #222' }}>
                <th style={{ padding: '6px 8px' }}>slug</th>
                <th style={{ padding: '6px 8px' }}>source</th>
                <th style={{ padding: '6px 8px' }}>scopes</th>
                <th style={{ padding: '6px 8px' }}>secrets</th>
                <th style={{ padding: '6px 8px' }}>disk</th>
                <th style={{ padding: '6px 8px' }}>status</th>
              </tr>
            </thead>
            <tbody>
              {clis.map((cli) => (
                <tr key={cli.slug} style={{ borderBottom: '1px solid #1a1a1a' }}>
                  <td style={{ padding: '6px 8px', color: '#eee', fontFamily: 'monospace' }}>{cli.slug}</td>
                  <td style={{ padding: '6px 8px', color: '#aaa' }}>{cli.source_kind}</td>
                  <td style={{ padding: '6px 8px', color: '#aaa' }}>{(cli.declared_scopes || []).join(', ') || '—'}</td>
                  <td style={{ padding: '6px 8px', color: '#aaa' }}>{(cli.required_secrets || []).length}</td>
                  <td style={{ padding: '6px 8px', color: '#aaa' }}>{cli.disk_usage ? `${Math.round((cli.disk_usage.bytes || 0) / 1024)} KB` : '—'}</td>
                  <td style={{ padding: '6px 8px', color: cli.status === 'active' ? '#9be39b' : '#c88' }}>{cli.status}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </section>
  );
}
