// Fleet dashboard: the weekly verdict. Live run banner, fleet KPIs (with
// WoW movement), the attention list of flagged regions, and the weekly
// trend. The full inventory table lives on /regions. Client component
// polling /api/v1/overview (+ runs for the trend) — 5s while a run is in
// flight, 60s idle.

"use client";

import { useCallback, useState } from "react";
import { fetchOverview, fetchRuns } from "@/lib/api-client";
import type { OverviewResponse, RunSummaryFile } from "@/lib/api-types";
import { POLL_FAST_MS, POLL_SLOW_MS, usePolling } from "@/lib/use-polling";
import { savingsPct } from "@/lib/run-metrics";
import { money, moneyDelta } from "@/lib/fmt";
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 { CurrentRunBanner } from "@/components/runs/CurrentRunBanner";
import { FleetTrendChart } from "@/components/dashboard/FleetTrendChart";
import { AttentionList } from "@/components/dashboard/AttentionList";
import { RunTriggerButton } from "@/components/runs/RunTriggerButton";

/** Fleet WoW movement: sum of per-region deltas (regions without a previous
 *  snapshot contribute nothing). */
function fleetWowDelta(regions: OverviewResponse["regions"]): number | null {
  let acc = 0;
  let seen = false;
  for (const r of regions) {
    if (typeof r.deltaMonthlyCostUsd === "number") {
      acc += r.deltaMonthlyCostUsd;
      seen = true;
    }
  }
  return seen ? acc : null;
}

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

  const load = useCallback(async (isCurrent: () => boolean) => {
    // The two fetches settle independently: overview is the page's backbone
    // (its failure IS the page's error), but a runs failure only costs the
    // trend an update — never the whole page.
    const [ov, rs] = await Promise.allSettled([fetchOverview(), fetchRuns(60)]);
    if (!isCurrent()) return;
    if (ov.status === "fulfilled") {
      setOverview(ov.value);
      setError(null);
    } else {
      setError(ov.reason instanceof Error ? ov.reason.message : String(ov.reason));
    }
    if (rs.status === "fulfilled") setRuns(rs.value.runs);
  }, []);

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

  if (error) return <ErrorBox message={error} onRetry={() => void reload()} />;
  if (!overview) return <Loading label="loading fleet overview…" />;

  const savingsShare = savingsPct(
    overview.fleet.totalMonthlyCostUsd,
    overview.fleet.totalPotentialMonthlySavingsUsd,
  );
  const wow = fleetWowDelta(overview.regions);

  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">Dashboard</h1>
        <RunTriggerButton
          totalRegions={overview.fleet.regionCount}
          label="Run Insight"
          variant="secondary"
          size="sm"
          onTriggered={() => void reload()}
        />
      </div>

      <CurrentRunBanner current={overview.currentRun} />

      <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
        <KpiCard
          label="Fleet monthly cost"
          value={money(overview.fleet.totalMonthlyCostUsd, 0)}
          sub={wow === null ? `${overview.fleet.regionCount} regions` : `${moneyDelta(wow)} WoW · ${overview.fleet.regionCount} regions`}
        />
        <KpiCard
          label="Potential monthly savings"
          value={money(overview.fleet.totalPotentialMonthlySavingsUsd, 0)}
          sub={
            (savingsShare === null ? undefined : `${savingsShare.toFixed(1)}% of cost · `) +
            "stability-confirmed only, needs manual verification"
          }
          tone="good"
        />
        <KpiCard
          label="Attention"
          value={String(overview.fleet.regionsPricingMissing)}
          sub={overview.fleet.regionsPricingMissing > 0 ? "regions missing pricing" : "all pricing covered"}
          tone={overview.fleet.regionsPricingMissing > 0 ? "warn" : "neutral"}
        />
      </div>

      <AttentionList regions={overview.regions} />

      <Section title="Weekly trend" subtitle="Fleet totals per run; savings from the best feasible scenario">
        <FleetTrendChart runs={runs} />
      </Section>
    </div>
  );
}
