import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { getTopic, getVerdict } from '../api';
import type { TopicDetail, Verdict } from '../types';
import { fmtTime } from '../util';

export function VerdictPage() {
  const { id } = useParams<{ id: string }>();
  const [topic, setTopic] = useState<TopicDetail | null>(null);
  const [verdict, setVerdict] = useState<Verdict | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    const ac = new AbortController();
    setLoading(true);
    Promise.all([getTopic(id, ac.signal), getVerdict(id, ac.signal)])
      .then(([t, v]) => {
        setTopic(t);
        setVerdict(v);
        setErr(null);
      })
      .catch((e: Error) => {
        if (e.name !== 'AbortError') setErr(e.message);
      })
      .finally(() => setLoading(false));
    return () => ac.abort();
  }, [id]);

  if (!id) return <div className="err">missing topic id</div>;
  if (loading) return <div className="muted">loading…</div>;
  if (err) return <div className="err">{err}</div>;
  if (!topic) return <div className="err">topic not found</div>;

  return (
    <div className="td">
      <div>
        <span className="eyebrow">verdict permalink</span>
        <h1>{topic.title}</h1>
        <p className="td-summary">{topic.summary}</p>
        <p className="muted" style={{ marginTop: 8 }}>
          schema: <code>{topic.verdict_schema_id}</code>
          {' · '}debate window: {fmtTime(topic.debate_start_at)} → {fmtTime(topic.debate_end_at)}
          {' · '}
          <Link to={`/topics/${topic.id}`}>back to topic</Link>
        </p>
      </div>

      {!verdict ? (
        <div className="panel td-empty">
          no verdict yet — topic status is <span className={`pill pill-${topic.status}`}>{topic.status}</span>
          {topic.status === 'debating' && ', judge has not submitted'}
          {topic.status === 'cancelled' && ', topic was cancelled before a verdict could be reached'}
        </div>
      ) : (
        <>
          <div className="panel">
            <div className="panel-header">verdict (structured)</div>
            <pre className="vd-json">{JSON.stringify(verdict.verdict, null, 2)}</pre>
            <div className="row muted" style={{ marginTop: 8, fontSize: '0.85em' }}>
              <span>judge: {verdict.judge_agent_id}</span>
              <span className="spacer" />
              <span>produced: {fmtTime(verdict.produced_at)}</span>
              {(verdict.tokens_input + verdict.tokens_output) > 0 && (
                <span>tokens: {verdict.tokens_input} in / {verdict.tokens_output} out</span>
              )}
            </div>
          </div>
          <div className="panel">
            <div className="panel-header">rationale</div>
            <div className="vd-rationale">{verdict.rationale}</div>
          </div>
        </>
      )}
    </div>
  );
}
