import { PanelFrame } from "./PanelFrame";
import type { RuntimeRun } from "../state/types";
import { JsonView } from "./JsonView";

interface RuntimePanelProps {
  runs: RuntimeRun[];
  selectedRunId: string;
  onSelectRun: (runId: string) => void;
  onStartRun: () => Promise<void> | void;
  onFinishRun: () => Promise<void> | void;
  onRefreshRuns: () => Promise<void> | void;
  onRunEval: () => Promise<void> | void;
  onCopyEvalReport: () => Promise<void> | void;
  evalBusy: boolean;
  traceItems: unknown[];
  evalReport: unknown;
}

export function RuntimePanel({
  runs,
  selectedRunId,
  onSelectRun,
  onStartRun,
  onFinishRun,
  onRefreshRuns,
  onRunEval,
  onCopyEvalReport,
  evalBusy,
  traceItems,
  evalReport
}: RuntimePanelProps) {
  return (
    <PanelFrame
      title="NDC Run Monitor"
      subtitle="Важно: кнопка Запустить run создает только run-сущность. Кнопка eval запускает batch-проверку normalizer v2.0.2."
    >
      <div className="button-row">
        <button type="button" onClick={() => onStartRun()}>
          Запустить run
        </button>
        <button type="button" onClick={() => onFinishRun()} disabled={!selectedRunId}>
          Завершить выбранный run
        </button>
        <button type="button" onClick={() => onRefreshRuns()}>
          Обновить runs
        </button>
        <button type="button" onClick={() => onRunEval()} disabled={evalBusy}>
          {evalBusy ? "Идет eval v2.0.2..." : "Запустить eval v2.0.2"}
        </button>
      </div>
      <div className="runtime-grid">
        <div className="runtime-runs">
          {runs.map((run) => (
            <button
              key={run.runId}
              type="button"
              className={selectedRunId === run.runId ? "history-item selected" : "history-item"}
              onClick={() => onSelectRun(run.runId)}
            >
              <div className="history-row">
                <strong>{run.status}</strong>
                <span>{run.runId}</span>
              </div>
              <div className="history-row">
                <span>{run.sessionId}</span>
                <span>{new Date(run.updatedAt).toLocaleString("ru-RU")}</span>
              </div>
            </button>
          ))}
          {runs.length === 0 ? <p className="muted">Нет активных запусков.</p> : null}
        </div>
        <div>
          <h3>Trace выбранного run</h3>
          <JsonView value={traceItems} />
          <div className="eval-report-wrap">
            <h3 style={{ marginTop: 12 }}>Отчет eval</h3>
            <JsonView value={evalReport ?? { note: "Eval пока не запускался" }} />
            <button type="button" className="copy-cube-button" title="Скопировать отчет eval" onClick={() => onCopyEvalReport()}>
              ⧉
            </button>
          </div>
        </div>
      </div>
    </PanelFrame>
  );
}
