// Run history + live progress: the runs table loads once, the current-run
// panel polls /api/v1/runs/current every 5s while a run is in flight and
// every 60s while idle (so a freshly started run shows up).

"use client";

import { useCallback, useRef, useState } from "react";
import { fetchCurrentRun, fetchRuns } from "@/lib/api-client";
import type { RunHeader, RunSummaryFile } from "@/lib/api-types";
import { POLL_FAST_MS, POLL_SLOW_MS, usePolling } from "@/lib/use-polling";
import { Section } from "@/components/ui/Section";
import { Loading } from "@/components/ui/Loading";
import { ErrorBox } from "@/components/ui/ErrorBox";
import { RunHeader as RunHeaderPanel } from "@/components/runs/RunHeader";
import { RunTriggerButton } from "@/components/runs/RunTriggerButton";
import { RunsTable } from "@/components/runs/RunsTable";

export default function RunsPage() {
  const [runs, setRuns] = useState<RunSummaryFile[] | null>(null);
  const [current, setCurrent] = useState<RunHeader | null>(null);
  const [error, setError] = useState<string | null>(null);
  const hadCurrent = useRef(false);

  const loadRuns = useCallback(async (isCurrent: () => boolean) => {
    try {
      const rs = await fetchRuns(60);
      if (!isCurrent()) return;
      setRuns(rs.runs);
      setError(null);
    } catch (e) {
      if (!isCurrent()) return;
      setError(e instanceof Error ? e.message : String(e));
    }
  }, []);

  const { load: reloadRuns } = usePolling(loadRuns);

  // Polling failures keep the last snapshot — only the initial load reports errors.
  const loadCurrent = useCallback(
    async (isCurrent: () => boolean) => {
      try {
        const r = await fetchCurrentRun();
        if (!isCurrent()) return;
        if (hadCurrent.current && r.currentRun == null) void reloadRuns(); // a run just finished
        hadCurrent.current = r.currentRun != null;
        setCurrent(r.currentRun);
      } catch {
        // transient — keep polling
      }
    },
    [reloadRuns],
  );

  const running = current != null;
  const { load: pollCurrent } = usePolling(loadCurrent, {
    intervalMs: running ? POLL_FAST_MS : POLL_SLOW_MS,
  });

  if (error) return <ErrorBox message={error} />;

  return (
    <div className="animate-fade-in space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h1 className="text-xl font-semibold tracking-tight">History</h1>
        <RunTriggerButton
          totalRegions={current ? Object.keys(current.regions).length : 0}
          label="Run Insight"
          variant="secondary"
          size="sm"
          onTriggered={() => {
            void pollCurrent();
            void reloadRuns();
          }}
        />
      </div>

      {current ? <RunHeaderPanel run={current} /> : null}

      <Section title="Run history" subtitle="last 60 fleet runs — newest first">
        {runs === null ? (
          <Loading label="loading runs…" />
        ) : (
          <RunsTable runs={runs} />
        )}
      </Section>
    </div>
  );
}
