"use client";

import { useEffect, useState } from "react";

import { DataTable } from "@/components/data-table";
import { SectionHeading } from "@/components/section-heading";
import { getRuns, getRunsSummary } from "@/lib/api/client";
import type { RunRecord, RunsSummary } from "@/lib/api/types";
import { useStream } from "@/lib/ws/use-stream";

export function RunsBoard({
  initialRuns,
  initialSummary,
}: {
  initialRuns: RunRecord[];
  initialSummary: RunsSummary;
}) {
  const [runs, setRuns] = useState(initialRuns);
  const [summary, setSummary] = useState(initialSummary);

  useStream((event) => {
    if (event.event === "run.updated") {
      void Promise.all([getRuns({ limit: 50 }), getRunsSummary()]).then(([nextRuns, nextSummary]) => {
        setRuns(nextRuns);
        setSummary(nextSummary);
      });
    }
  });

  useEffect(() => {
    setRuns(initialRuns);
    setSummary(initialSummary);
  }, [initialRuns, initialSummary]);

  return (
    <div className="pageStack">
      <SectionHeading
        kicker="Runs"
        title="Run observability"
        description="Gap and failure inspection for archiver and pipeline producers."
      />
      <div className="inlineSummary">
        RUNS: <strong>{summary.total_runs}</strong> total
        <span className="sep">|</span>
        <strong style={{ color: "var(--ok)" }}>{summary.success_count}</strong> ok
        <span className="sep">|</span>
        <strong style={{ color: "var(--warn)" }}>{summary.gap_count}</strong> gaps
        <span className="sep">|</span>
        <strong style={{ color: "var(--danger)" }}>{summary.failed_count}</strong> failed
      </div>
      <DataTable
        columns={[
          "run_id",
          "logical_ts",
          "dataset",
          "status",
          "rows_written_raw",
          "rows_written_normalized",
          "duration_ms",
        ]}
        rows={runs}
        statusColumn="status"
      />
    </div>
  );
}
