// Insight, organized as an inspection decision path: Cost (how much
// and why) → Workloads (who uses it) → Nodes (where it runs) →
// Recommendations (what to change).
// The active tab lives in ?tab= so a finding can be linked directly. All
// artifacts arrive in a single RegionDetailResponse; every section tolerates
// a missing artifact (failed stage) via its own Empty state. A region
// switcher in the header hops between regions without leaving the page.

"use client";

import { Suspense, useCallback, useState } from "react";
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation";
import { fetchRegionDetail, fetchRegionHistory } from "@/lib/api-client";
import { usePolling } from "@/lib/use-polling";
import type { HistoryResponse, RegionDetailResponse } from "@/lib/api-types";
import type { RegionResolution } from "@/engine/resolve";
import type { ReportModel } from "@/engine/report-model";
import type { Inventory } from "@/engine/inventory";
import type { WorkloadRow } from "@/engine/classify";
import type { PricingCoverageResult } from "@/engine/pricing";
import { money, num, utc8Stamp } from "@/lib/fmt";
import { Section } from "@/components/ui/Section";
import { Badge } from "@/components/ui/Badge";
import { Empty } from "@/components/ui/Empty";
import { Loading } from "@/components/ui/Loading";
import { ErrorBox } from "@/components/ui/ErrorBox";
import { KpiCard } from "@/components/ui/KpiCard";
import { PricingCoverageBanner } from "@/components/regions/PricingCoverageBanner";
import { CostOverviewCards } from "@/components/regions/CostOverviewCards";
import { CostOverviewTable } from "@/components/regions/CostOverviewTable";
import { RegionTrendChart } from "@/components/regions/RegionTrendChart";
import { ScenarioComparison } from "@/components/regions/ScenarioComparison";
import { WorkloadTable } from "@/components/regions/WorkloadTable";
import { NodegroupTable } from "@/components/regions/NodegroupTable";
import { PerNodeDistribution } from "@/components/regions/PerNodeDistribution";
import { ReductionOpportunities } from "@/components/regions/ReductionOpportunities";
import { RegionSwitcher } from "@/components/regions/RegionSwitcher";
import { PillTabs } from "@/components/ui/PillTabs";
import { useRegionKeys } from "@/lib/use-region-keys";

const TABS = [
  { id: "cost", label: "Cost" },
  { id: "workloads", label: "Workloads" },
  { id: "nodes", label: "Nodes" },
  { id: "recommendations", label: "Recommendations" },
] as const;

type TabId = (typeof TABS)[number]["id"];

function isTabId(v: string | null): v is TabId {
  return v !== null && TABS.some((t) => t.id === v);
}

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

function RegionDetailInner() {
  const params = useParams<{ regionKey: string | string[] }>();
  const regionKey = Array.isArray(params?.regionKey) ? params.regionKey[0] : params?.regionKey;
  const search = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const tabParam = search.get("tab");
  const tab: TabId = isTabId(tabParam) ? tabParam : "cost";

  const [detail, setDetail] = useState<RegionDetailResponse | null>(null);
  const [history, setHistory] = useState<HistoryResponse["points"]>([]);
  const [error, setError] = useState<string | null>(null);
  const regionKeys = useRegionKeys();

  // Sequence-guarded by usePolling: switching regions re-fires the load
  // while the previous one may still be in flight — only the latest may
  // touch state.
  const load = useCallback(
    async (isCurrent: () => boolean) => {
      if (!regionKey) return;
      try {
        const [d, h] = await Promise.all([
          fetchRegionDetail(regionKey),
          fetchRegionHistory(regionKey, 26),
        ]);
        if (!isCurrent()) return;
        setDetail(d);
        setHistory(h.points);
        setError(null);
      } catch (e) {
        if (!isCurrent()) return;
        setError(e instanceof Error ? e.message : String(e));
      }
    },
    [regionKey],
  );

  const { refresh } = usePolling(load);

  if (error) return <ErrorBox message={error} onRetry={() => void refresh()} />;
  if (!detail) return <Loading label={`loading region detail${regionKey ? ` for ${regionKey}` : ""}…`} />;

  // Partial<RegionArtifacts> is fully typed — each artifact is present or
  // undefined on a partial run, no casts needed.
  const summary = detail.summary;
  const report: ReportModel | undefined = detail.detail["report-model"];
  const workloads: WorkloadRow[] = detail.detail.workloads?.workloads ?? [];
  const inventory: Inventory | undefined = detail.detail.inventory;
  const coverage: PricingCoverageResult | undefined = detail.detail.pricingCoverage;
  const resolve: RegionResolution | undefined = detail.detail.resolve;

  const switchTab = (id: TabId): void => {
    router.replace(`${pathname}?tab=${id}`, { scroll: false });
  };

  // Run diagnostics (id, region resolution, dataplane) are hover-only —
  // noise in the visible header, useful on demand.
  const runTooltip = [
    detail.runId,
    resolve ? `resolved ${resolve.inputRegion} → ${resolve.normalizedRegion} (${resolve.selectionReason})` : null,
    resolve ? `dataplane ${resolve.dataplaneAddress}` : null,
  ]
    .filter(Boolean)
    .join(" · ");

  return (
    <div className="animate-fade-in space-y-4">
      <div>
        <div className="flex items-center gap-2">
          <h1 className="font-mono text-lg font-semibold tracking-tight">{detail.regionKey}</h1>
          <Badge tone="info">{summary.vendor}</Badge>
          <RegionSwitcher
            regionKeys={regionKeys}
            value={regionKey ?? detail.regionKey}
            onSelect={(rk) => router.push(`/insight/${rk}?tab=${tab}`)}
          />
        </div>
        <p className="mt-0.5 flex items-center gap-1 text-xs text-text-muted" title={runTooltip}>
          Finished {utc8Stamp(summary.finishedAt)}
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            className="h-3 w-3"
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <circle cx="12" cy="12" r="9" />
            <line x1="12" y1="11" x2="12" y2="16" />
            <circle cx="12" cy="8" r="0.5" fill="currentColor" stroke="none" />
          </svg>
        </p>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
        <KpiCard label="Cost/mo" value={money(summary.monthlyCostUsd)} />
        <KpiCard
          label="Savings/mo"
          value={money(summary.potentialMonthlySavingsUsd)}
          tone="good"
        />
        <KpiCard label="Nodes" value={num(summary.nodeCount)} />
        <KpiCard label="Workloads" value={num(summary.workloadCount)} />
      </div>

      {coverage ? <PricingCoverageBanner coverage={coverage} /> : null}

      <PillTabs
        items={TABS}
        value={tab}
        onSelect={(id) => {
          if (isTabId(id)) switchTab(id);
        }}
      />

      {tab === "cost" ? (
        <>
          {report ? (
            <CostOverviewCards cost={report.costOverview} savings={summary.potentialMonthlySavingsUsd} />
          ) : null}

          <Section title="Cost overview" subtitle="nodegroup unit arithmetic + vmstorage storage, monthly USD">
            {report ? (
              <CostOverviewTable cost={report.costOverview} />
            ) : (
              <Empty>Report model missing for this run — cost overview unavailable.</Empty>
            )}
          </Section>

          <Section title="Cost trend" subtitle="monthly cost and potential savings per run, last 26 weeks">
            <RegionTrendChart points={history} />
          </Section>
        </>
      ) : null}

      {tab === "workloads" ? (
        <>
          <Section
            title="Workloads"
            subtitle="per-workload usage, rightsized requests and rationale — click a row for detail"
          >
            <WorkloadTable workloads={workloads} regionKey={detail.regionKey} />
          </Section>

        </>
      ) : null}

      {tab === "nodes" ? (
        <>
          <Section title="Nodegroups" subtitle="cluster inventory composition">
            {inventory ? (
              <NodegroupTable nodegroups={inventory.nodegroups} specByType={coverage?.computeSpec} />
            ) : (
              <Empty>Inventory missing for this run.</Empty>
            )}
          </Section>

          <Section
            title="Per-node distribution"
            subtitle="requested cpu/mem vs allocatable — pod counts exclude DaemonSet pods"
          >
            {report && report.perNodeDistribution.length > 0 ? (
              <PerNodeDistribution rows={report.perNodeDistribution} regionKey={detail.regionKey} />
            ) : (
              <Empty>No per-node distribution — inventory collected no nodes.</Empty>
            )}
          </Section>
        </>
      ) : null}

      {tab === "recommendations" ? (
        <>
          <Section
            title="Shrink recommendation"
            subtitle="immediate and conditional opportunities — every recommendation requires manual verification"
          >
            <ScenarioComparison
              evaluation={detail.detail.scenarios ?? undefined}
              streak={summary.stabilityStreak ?? null}
              workloads={workloads}
            />
          </Section>

          <Section
            title="Reduction opportunities"
            subtitle="nodegroups that could shed nodes or downsize after rightsizing"
          >
            {report ? (
              <ReductionOpportunities data={report.reductionOpportunities} />
            ) : (
              <Empty>Report model missing for this run — reduction analysis unavailable.</Empty>
            )}
          </Section>
        </>
      ) : null}
    </div>
  );
}
