// Region-level compare between two runs: nodegroup counts, best scenario,
// and the workload diff (added/removed/changed). runA/runB arrive as query
// params from the fleet compare; without them we fall back to the two most
// recent completed (success or partial) runs.

"use client";

import { Suspense, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { fetchRegionCompare, fetchComparableRuns } from "@/lib/api-client";
import type { RegionCompareResponse } from "@/lib/api-types";
import { Section } from "@/components/ui/Section";
import { KpiCard } from "@/components/ui/KpiCard";
import { Loading } from "@/components/ui/Loading";
import { ErrorBox } from "@/components/ui/ErrorBox";
import { NodegroupDiffTable } from "@/components/compare/NodegroupDiffTable";
import { WorkloadDiff } from "@/components/compare/WorkloadDiff";

export default function RegionComparePage() {
  // useSearchParams needs a Suspense boundary for static prerendering.
  return (
    <Suspense fallback={<Loading label="loading comparison…" />}>
      <RegionCompareInner />
    </Suspense>
  );
}

function RegionCompareInner() {
  const params = useParams<{ regionKey: string | string[] }>();
  const regionKey = Array.isArray(params?.regionKey) ? params.regionKey[0] : (params?.regionKey ?? "");
  const search = useSearchParams();
  const runAParam = search.get("runA");
  const runBParam = search.get("runB");

  const [data, setData] = useState<RegionCompareResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!regionKey) return;
    let cancelled = false;
    (async () => {
      try {
        let runA = runAParam;
        let runB = runBParam;
        if (!runA || !runB) {
          const completed = await fetchComparableRuns();
          if (completed.length < 2) {
            throw new Error("need two completed runs to compare — analyze the fleet first");
          }
          runB = runB ?? completed[0].runId;
          runA = runA ?? completed[1].runId;
        }
        const resp = await fetchRegionCompare(regionKey, runA, runB);
        if (!cancelled) {
          setData(resp);
          setError(null);
        }
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : String(e));
          setData(null);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [regionKey, runAParam, runBParam]);

  if (error) return <ErrorBox message={error} />;
  if (!data) return <Loading label="comparing runs…" />;

  const { diff } = data;
  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-lg font-semibold text-text-primary">{data.regionKey}</h1>
          <p className="mt-0.5 text-xs text-text-muted">
            A <span className="font-mono">{data.runA}</span> vs B{" "}
            <span className="font-mono">{data.runB}</span>
          </p>
        </div>
        <nav className="flex gap-4 text-sm">
          <Link className="text-accent hover:underline" href="/compare">
            ← fleet compare
          </Link>
          <Link className="text-accent hover:underline" href={`/insight/${data.regionKey}`}>
            region insight
          </Link>
        </nav>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <KpiCard label="Best scenario A" value={diff.bestScenarioA ?? "—"} />
        <KpiCard label="Best scenario B" value={diff.bestScenarioB ?? "—"} />
      </div>

      <Section title="Nodegroups" subtitle="matched by name — instance types and counts per side">
        <NodegroupDiffTable nodegroups={diff.nodegroups} />
      </Section>

      <Section title="Workloads" subtitle="matched by namespace/kind/name">
        <WorkloadDiff workloads={diff.workloads} />
      </Section>
    </div>
  );
}
