import { useState } from 'react';
import { useRunJob, useAiProposals } from '@insignia/iios-ai-web';
import type { AiArtifact } from '@insignia/iios-kernel-client';

export const SERVICE = 'http://localhost:3200';

const STATUS_COLORS: Record<string, string> = {
  PROPOSED: '#d97706',
  ACCEPTED: '#16a34a',
  REJECTED: '#dc2626',
  SUPERSEDED: '#6b7280',
};

/** Inject a signed dev webhook and poll the raw-event log until it normalizes into an interaction. */
async function ingestTestMessage(token: string, text: string): Promise<string> {
  const inject = await fetch(`${SERVICE}/v1/dev/webhook/WEBHOOK`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ text }),
  });
  if (!inject.ok) throw new Error(`inject ${inject.status}`);
  const { rawEventId } = (await inject.json()) as { rawEventId: string };
  for (let i = 0; i < 40; i++) {
    const r = await fetch(`${SERVICE}/v1/adapters/inbound`, { headers: { authorization: `Bearer ${token}` } });
    const rows = (await r.json()) as Array<{ id: string; interactionId?: string | null }>;
    const hit = rows.find((x) => x.id === rawEventId);
    if (hit?.interactionId) return hit.interactionId;
    await new Promise((res) => setTimeout(res, 150));
  }
  throw new Error('interaction never normalized');
}

const box: React.CSSProperties = { border: '1px solid #e5e7eb', borderRadius: 8, padding: 16, marginBottom: 16 };
const card: React.CSSProperties = { border: '1px solid #e5e7eb', borderRadius: 8, padding: 12, marginBottom: 10 };

export function App({ token }: { token: string }) {
  const runJob = useRunJob();
  const [interactionId, setInteractionId] = useState<string | null>(null);
  const [text, setText] = useState('There is a party at 9 PM tonight!');
  const [busy, setBusy] = useState('');
  const { artifacts, accept, reject } = useAiProposals({ interactionId: interactionId ?? undefined, pollMs: 2500 });

  const spent = artifacts.reduce((sum, a) => sum + (a.modelRun?.costUnits ?? 0), 0);

  const ingest = async () => {
    setBusy('ingesting…');
    try {
      setInteractionId(await ingestTestMessage(token, text));
      setBusy('');
    } catch (e) {
      setBusy(`error: ${(e as Error).message}`);
    }
  };

  const run = async (jobType: 'CLASSIFY' | 'SUMMARIZE' | 'EXTRACT') => {
    if (!interactionId) return;
    setBusy(`running ${jobType}…`);
    try {
      await runJob(interactionId, jobType);
      setBusy('');
    } catch (e) {
      setBusy(`error: ${(e as Error).message}`);
    }
  };

  return (
    <div style={{ padding: 24, fontFamily: 'sans-serif', maxWidth: 860, margin: '0 auto' }}>
      <h2>IIOS P7 — AI Studio</h2>
      <p style={{ color: '#666' }}>
        AI only <b>proposes</b>. Nothing here sends or approves a route — an AI flag still needs human approval in Route Admin (KG-05).
      </p>

      <div style={box}>
        <h3>1 · Ingest a message</h3>
        <div style={{ display: 'flex', gap: 8 }}>
          <input value={text} onChange={(e) => setText(e.target.value)} style={{ flex: 1 }} />
          <button onClick={() => void ingest()}>Ingest</button>
        </div>
        {interactionId && <p style={{ color: '#16a34a' }}>interaction: {interactionId}</p>}
        {busy && <p style={{ color: '#666' }}>{busy}</p>}
      </div>

      <div style={box}>
        <h3>2 · Run a worker</h3>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button disabled={!interactionId} onClick={() => void run('CLASSIFY')}>Classify</button>
          <button disabled={!interactionId} onClick={() => void run('SUMMARIZE')}>Summarize</button>
          <button disabled={!interactionId} onClick={() => void run('EXTRACT')}>Extract</button>
          <span style={{ marginLeft: 'auto', color: '#666' }}>💸 budget spent: <b>{spent}</b> units</span>
        </div>
      </div>

      <div style={box}>
        <h3>3 · Proposals</h3>
        {artifacts.length === 0 && <p style={{ color: '#666' }}>No proposals yet — run a worker above.</p>}
        {artifacts.map((a) => (
          <ProposalCard key={a.id} a={a} onAccept={() => void accept(a.id)} onReject={() => void reject(a.id)} />
        ))}
      </div>
    </div>
  );
}

function ProposalCard({ a, onAccept, onReject }: { a: AiArtifact; onAccept: () => void; onReject: () => void }) {
  const content = a.contentRef as { text?: string; flags?: string[]; claims?: unknown[] };
  return (
    <div style={card}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <strong>{a.artifactType}</strong>
        <span style={{ color: STATUS_COLORS[a.status] ?? '#000', fontWeight: 600 }}>{a.status}</span>
        <span style={{ color: '#666' }}>confidence {a.confidence ?? '—'}</span>
        {a.abstentionReason && <span style={{ color: '#dc2626' }}>abstained: {a.abstentionReason}</span>}
        <span style={{ marginLeft: 'auto', color: '#999', fontSize: 12 }}>
          {a.modelRun?.model} · {a.modelRun?.costUnits} units · {a.modelRun?.tokensIn}→{a.modelRun?.tokensOut} tok
        </span>
      </div>
      <div style={{ color: '#333', marginTop: 6 }}>
        {content.text ?? (content.flags ? `flags: ${content.flags.join(', ') || '(none)'}` : JSON.stringify(content))}
      </div>
      {a.explanationRef && <div style={{ color: '#888', fontSize: 12, marginTop: 4 }}>{a.explanationRef}</div>}
      {a.evidence && a.evidence.length > 0 && (
        <div style={{ color: '#888', fontSize: 12, marginTop: 4 }}>
          cites: {a.evidence.map((e) => `${e.sourceType}:${e.sourceId.slice(0, 8)}`).join(', ')}
        </div>
      )}
      {a.claims && a.claims.length > 0 && (
        <ul style={{ margin: '6px 0 0', color: '#555', fontSize: 13 }}>
          {a.claims.map((c) => (
            <li key={c.id}>
              {c.claimType}: {JSON.stringify(c.claimJson)} <span style={{ color: '#999' }}>[{c.validationStatus}]</span>
            </li>
          ))}
        </ul>
      )}
      {a.status === 'PROPOSED' && (
        <div style={{ marginTop: 8 }}>
          <button onClick={onAccept} style={{ marginRight: 6 }}>Accept</button>
          <button onClick={onReject}>Reject</button>
        </div>
      )}
    </div>
  );
}
