// Regions table: one row per region's latest snapshot, sortable; the
// region name links into the Insight page.

import { useMemo, useState } from "react";
import Link from "next/link";
import type { RegionOverviewRow } from "@/lib/api-types";
import { money, moneyDelta, num, pct, deltaTone } from "@/lib/fmt";
import { savingsPct } from "@/lib/run-metrics";
import { Badge } from "@/components/ui/Badge";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

type SortKey =
  | "regionKey"
  | "vendor"
  | "monthlyCostUsd"
  | "deltaMonthlyCostUsd"
  | "potentialMonthlySavingsUsd"
  | "savingsPct"
  | "nodeCount"
  | "idleCount"
  | "reverseAdjustmentCount";

export function RegionsTable({ regions }: { regions: RegionOverviewRow[] }) {
  const [sortKey, setSortKey] = useState<SortKey>("monthlyCostUsd");
  const [desc, setDesc] = useState(true);

  const sorted = useMemo(() => {
    const val = (r: RegionOverviewRow): number | string => {
      switch (sortKey) {
        case "regionKey":
          return r.regionKey;
        case "vendor":
          return r.vendor;
        case "deltaMonthlyCostUsd":
          return r.deltaMonthlyCostUsd ?? -Infinity;
        case "potentialMonthlySavingsUsd":
          return r.potentialMonthlySavingsUsd ?? -Infinity;
        case "savingsPct":
          return savingsPct(r.monthlyCostUsd, r.potentialMonthlySavingsUsd) ?? -Infinity;
        case "nodeCount":
          return r.nodeCount ?? -Infinity;
        case "idleCount":
          return r.idleCount ?? -Infinity;
        case "reverseAdjustmentCount":
          return r.reverseAdjustmentCount ?? -Infinity;
        default:
          return r.monthlyCostUsd ?? -Infinity;
      }
    };
    const rows = [...regions].sort((a, b) => {
      const va = val(a);
      const vb = val(b);
      const cmp = typeof va === "number" && typeof vb === "number" ? va - vb : String(va).localeCompare(String(vb));
      return desc ? -cmp : cmp;
    });
    return rows;
  }, [regions, sortKey, desc]);

  // Numbers default to biggest-first (cost, counts); text reads top-down
  // ascending on first click.
  const toggle = (key: SortKey, numeric: boolean) => {
    if (key === sortKey) {
      setDesc((d) => !d);
    } else {
      setSortKey(key);
      setDesc(numeric);
    }
  };
  const sortedMarker = (key: SortKey) => (sortKey === key ? (desc ? "desc" : "asc") : false);

  if (regions.length === 0) {
    return <Empty>No regions match the current filters.</Empty>;
  }

  return (
    <div>
      <DataTable>
        <thead>
          <tr>
            <Th onClick={() => toggle("regionKey", false)} sorted={sortedMarker("regionKey")}>Region</Th>
            <Th onClick={() => toggle("vendor", false)} sorted={sortedMarker("vendor")}>Vendor</Th>
            <Th numeric onClick={() => toggle("monthlyCostUsd", true)} sorted={sortedMarker("monthlyCostUsd")}>Cost/mo</Th>
            <Th numeric onClick={() => toggle("deltaMonthlyCostUsd", true)} sorted={sortedMarker("deltaMonthlyCostUsd")}>Δ WoW</Th>
            <Th numeric onClick={() => toggle("potentialMonthlySavingsUsd", true)} sorted={sortedMarker("potentialMonthlySavingsUsd")}>Savings/mo</Th>
            <Th numeric onClick={() => toggle("savingsPct", true)} sorted={sortedMarker("savingsPct")}>%</Th>
            <Th>Best scenario</Th>
            <Th numeric onClick={() => toggle("nodeCount", true)} sorted={sortedMarker("nodeCount")}>Nodes</Th>
            <Th
              numeric
              onClick={() => toggle("idleCount", true)}
              sorted={sortedMarker("idleCount")}
              title="Workloads whose observed per-pod peak CPU stayed below 5% of their request — effectively idle; recommended to shrink to floor"
            >
              Idle workloads
            </Th>
            <Th
              numeric
              onClick={() => toggle("reverseAdjustmentCount", true)}
              sorted={sortedMarker("reverseAdjustmentCount")}
              title="Workloads whose observed peak usage exceeded their request (CPU or memory) — requests should be raised; reliability risk"
            >
              Raise req
            </Th>
            <Th>Pricing</Th>
          </tr>
        </thead>
        <tbody>
          {sorted.map((r) => {
            const share = savingsPct(r.monthlyCostUsd, r.potentialMonthlySavingsUsd);
            return (
              <tr key={r.regionKey} className="transition-colors hover:bg-surface-1">
                <Td>
                  <Link
                    href={`/insight/${r.regionKey}`}
                    className="font-mono text-[13px] font-medium text-accent hover:underline"
                  >
                    {r.regionKey}
                  </Link>
                </Td>
                <Td><span className="text-text-muted">{r.vendor}</span></Td>
                <Td numeric>{money(r.monthlyCostUsd)}</Td>
                <Td numeric className={deltaTone(r.deltaMonthlyCostUsd, true)}>
                  {moneyDelta(r.deltaMonthlyCostUsd)}
                </Td>
                <Td numeric className={deltaTone(r.potentialMonthlySavingsUsd, false)}>
                  {money(r.potentialMonthlySavingsUsd)}
                </Td>
                <Td numeric>{share === null ? "—" : pct(share, 1)}</Td>
                <Td>
                  {r.bestScenario ? (
                    <span className="text-text-secondary">{r.bestScenario}</span>
                  ) : (
                    <span className="text-text-muted">—</span>
                  )}
                </Td>
                <Td numeric>{num(r.nodeCount)}</Td>
                <Td numeric>{num(r.idleCount)}</Td>
                <Td numeric>{num(r.reverseAdjustmentCount)}</Td>
                <Td>
                  {r.pricingMissing ? (
                    <Badge tone="warn" title={(r.pricingMissingTypes ?? []).join(", ")}>
                      missing
                    </Badge>
                  ) : (
                    <Badge tone="good">ok</Badge>
                  )}
                </Td>
              </tr>
            );
          })}
        </tbody>
      </DataTable>
    </div>
  );
}
