// Regions list: the full fleet inventory with a search filter and sortable
// columns. Polls /api/v1/overview with the same cadence as the dashboard
// (5s while a run is in flight, 60s idle).

"use client";

import { useCallback, useMemo, useState } from "react";
import { fetchOverview } from "@/lib/api-client";
import type { OverviewResponse } from "@/lib/api-types";
import { POLL_FAST_MS, POLL_SLOW_MS, usePolling } from "@/lib/use-polling";
import { utc8Stamp } from "@/lib/fmt";
import { Section } from "@/components/ui/Section";
import { ErrorBox } from "@/components/ui/ErrorBox";
import { CurrentRunBanner } from "@/components/runs/CurrentRunBanner";
import { RegionFilters } from "@/components/regions/RegionFilters";
import { RegionsSkeleton } from "@/components/regions/RegionsSkeleton";
import { RegionsTable } from "@/components/regions/RegionsTable";

export default function RegionsPage() {
  const [overview, setOverview] = useState<OverviewResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  const [search, setSearch] = useState("");

  const load = useCallback(async (isCurrent: () => boolean) => {
    try {
      const ov = await fetchOverview();
      if (!isCurrent()) return;
      setOverview(ov);
      setError(null);
    } catch (e) {
      if (!isCurrent()) return;
      setError(e instanceof Error ? e.message : String(e));
    }
  }, []);

  // Poll while a run is in progress; otherwise poll slowly for freshness.
  const running = overview?.currentRun != null;
  const { refresh } = usePolling(load, {
    intervalMs: running ? POLL_FAST_MS : POLL_SLOW_MS,
  });

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return (overview?.regions ?? []).filter((r) => !q || r.regionKey.toLowerCase().includes(q));
  }, [overview, search]);

  if (error) return <ErrorBox message={error} onRetry={() => void refresh()} />;
  if (!overview) return <RegionsSkeleton />;

  return (
    <div className="animate-fade-in space-y-4">
      <div>
        <h1 className="text-xl font-semibold tracking-tight">
          Regions{" "}
          <span className="font-normal text-base text-text-muted">
            ({overview.fleet.regionCount} total)
          </span>
        </h1>
        <p className="mt-0.5 text-sm text-text-muted">
          latest snapshot per region — generated {utc8Stamp(overview.generatedAt)}
        </p>
      </div>

      <CurrentRunBanner current={overview.currentRun} />

      <RegionFilters search={search} onSearchChange={setSearch} />

      <Section title="Inventory">
        <RegionsTable regions={filtered} />
      </Section>
    </div>
  );
}
