"use client";

import { useEffect, useMemo, useState } from "react";
import { Braces, Database, FileCheck2, X } from "lucide-react";

import { fetchArtifact } from "@/lib/api";
import type { JourneyStep, JourneyView, RunSummary } from "@/lib/types";

export function EvidencePanel({
  journey,
  run,
  step,
  onClose,
}: {
  journey: JourneyView;
  run: RunSummary | null;
  step: JourneyStep | null;
  onClose: () => void;
}) {
  const [artifact, setArtifact] = useState<Record<string, unknown> | null>(null);
  const [artifactError, setArtifactError] = useState<string | null>(null);
  const artifactId = useMemo(() => firstArtifactId(step), [step]);

  useEffect(() => {
    setArtifact(null);
    setArtifactError(null);
  }, [step?.step_id]);

  if (!step) {
    return (
      <aside className="evidence-panel">
        <PanelHeader title="原始证据" onClose={onClose} />
        <div className="evidence-empty">先在左侧选择一个创作步骤。</div>
      </aside>
    );
  }

  async function loadArtifact() {
    if (artifactId === null) return;
    try {
      setArtifact(await fetchArtifact(journey.script_build_id, artifactId));
    } catch (reason) {
      setArtifactError(reason instanceof Error ? reason.message : "无法读取 Artifact");
    }
  }

  return (
    <aside className="evidence-panel">
      <PanelHeader title={step.title} onClose={onClose} />
      <div className="evidence-scroll">
        <section className="evidence-summary">
          <span>{step.process.actor}</span>
          <p>{step.reasoning}</p>
          <dl>
            <div><dt>Step</dt><dd>#{step.sequence}</dd></div>
            <div><dt>Root Trace</dt><dd>{journey.root_trace_id}</dd></div>
            <div><dt>Task</dt><dd>{step.task_id}</dd></div>
            {step.attempt_id ? <div><dt>Attempt</dt><dd>{step.attempt_id}</dd></div> : null}
            {step.validation_id ? <div><dt>Validation</dt><dd>{step.validation_id}</dd></div> : null}
            {step.decision_id ? <div><dt>Decision</dt><dd>{step.decision_id}</dd></div> : null}
            <div><dt>Input</dt><dd>{journey.input_summary.snapshot_id}</dd></div>
            <div><dt>Digest</dt><dd>{journey.input_summary.digest}</dd></div>
            {run?.started_at ? <div><dt>开始时间</dt><dd>{run.started_at}</dd></div> : null}
            {run?.completed_at ? <div><dt>结束时间</dt><dd>{run.completed_at}</dd></div> : null}
          </dl>
        </section>

        <EvidenceBlock
          icon={Braces}
          title="Process 运行元数据"
          value={{
            actor: step.process.actor,
            tool_name: step.process.tool_name,
            trace_id: step.process.trace_id,
            details: step.process.details,
            model: step.model,
            tokens: step.tokens,
            cost: step.cost,
            duration_ms: step.duration_ms,
          }}
        />

        {step.evidence.contract ? (
          <EvidenceBlock icon={FileCheck2} title="冻结的 TaskContract" value={step.evidence.contract} />
        ) : null}
        {step.evidence.tool_calls.length ? (
          <EvidenceBlock icon={Braces} title="真实工具调用" value={step.evidence.tool_calls} />
        ) : null}
        {step.evidence.validation ? (
          <EvidenceBlock icon={FileCheck2} title="Validation 结果" value={step.evidence.validation} />
        ) : null}
        {step.evidence.decision ? (
          <EvidenceBlock icon={FileCheck2} title="PlannerDecision" value={step.evidence.decision} />
        ) : null}

        {artifactId !== null ? (
          <section className="artifact-reader">
            <header><Database size={15} /><strong>Artifact 内容</strong></header>
            {artifact ? <pre>{JSON.stringify(artifact, null, 2)}</pre> : (
              <button type="button" onClick={loadArtifact}>从 Host 读取 Artifact #{artifactId}</button>
            )}
            {artifactError ? <p role="alert">{artifactError}</p> : null}
          </section>
        ) : null}
      </div>
    </aside>
  );
}

function PanelHeader({ title, onClose }: { title: string; onClose: () => void }) {
  return (
    <header className="evidence-header">
      <div><span>原始证据</span><h2>{title}</h2></div>
      <button type="button" onClick={onClose} aria-label="关闭证据面板"><X size={18} /></button>
    </header>
  );
}

function EvidenceBlock({ icon: Icon, title, value }: { icon: typeof FileCheck2; title: string; value: unknown }) {
  return (
    <details className="evidence-block" open>
      <summary><Icon size={15} /><span>{title}</span></summary>
      <pre>{JSON.stringify(value, null, 2)}</pre>
    </details>
  );
}

function firstArtifactId(step: JourneyStep | null): number | null {
  for (const item of step?.evidence.artifact_refs ?? []) {
    const uri = typeof item.uri === "string" ? item.uri : "";
    const match = uri.match(/^script-build:\/\/artifact-versions\/(\d+)$/);
    if (match) return Number(match[1]);
  }
  return null;
}
