// Region delta table for the two-date fleet compare: sorted by |cost Δ|
// (nulls last — the server's diffOverview order, rendered as delivered),
// with added/removed regions called out above the table and fallback
// asterisks marking costs pulled from an older run.

import Link from "next/link";
import { comparePairQuery } from "@/lib/api-client";
import type { OverviewDiff } from "@/lib/api-types";
import { deltaTone, money, moneyDelta } from "@/lib/fmt";
import { Badge } from "@/components/ui/Badge";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

function CostCell({ value, fallbackRunId }: { value: number | null; fallbackRunId?: string }) {
  return (
    <span title={fallbackRunId ? `value from fallback run ${fallbackRunId}` : undefined}>
      {money(value)}
      {fallbackRunId ? <span className="ml-0.5 text-text-muted">*</span> : null}
    </span>
  );
}

function ScenarioCell({ name }: { name: string | null }) {
  return name ? (
    <span className="text-text-secondary">{name}</span>
  ) : (
    <span className="text-text-muted">—</span>
  );
}

export function RegionDeltaTable({ diff }: { diff: OverviewDiff }) {
  // diffOverview already orders regions by |cost Δ| desc, nulls last.
  const rows = diff.regions;
  const linkFor = (regionKey: string) =>
    `/compare/${regionKey}?${comparePairQuery(diff.runIdA, diff.runIdB)}`;
  const hasFallback = rows.some((r) => r.fallbackA != null || r.fallbackB != null);

  return (
    <div className="space-y-3">
      {(diff.addedRegions.length > 0 || diff.removedRegions.length > 0) && (
        <div className="space-y-2 text-sm">
          {diff.addedRegions.length > 0 && (
            <div className="flex flex-wrap items-center gap-2">
              <span className="text-xs font-medium uppercase tracking-wide text-text-muted">Added</span>
              {diff.addedRegions.map((key) => (
                <span key={key} className="inline-flex items-center gap-1">
                  <Badge tone="info">new</Badge>
                  <Link className="text-accent hover:underline" href={linkFor(key)}>
                    {key}
                  </Link>
                </span>
              ))}
            </div>
          )}
          {diff.removedRegions.length > 0 && (
            <div className="flex flex-wrap items-center gap-2">
              <span className="text-xs font-medium uppercase tracking-wide text-text-muted">Removed</span>
              {diff.removedRegions.map((key) => (
                <span key={key} className="inline-flex items-center gap-1">
                  <Badge tone="warn">gone</Badge>
                  <Link className="text-accent hover:underline" href={linkFor(key)}>
                    {key}
                  </Link>
                </span>
              ))}
            </div>
          )}
        </div>
      )}

      {rows.length === 0 ? (
        <Empty>No regions to compare.</Empty>
      ) : (
        <DataTable>
          <thead>
            <tr>
              <Th>Region</Th>
              <Th>Vendor</Th>
              <Th numeric>Cost A</Th>
              <Th numeric>Cost B</Th>
              <Th numeric>Δ cost</Th>
              <Th numeric>Savings A</Th>
              <Th numeric>Savings B</Th>
              <Th>Best A</Th>
              <Th>Best B</Th>
              <Th>Presence</Th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => {
              const added = r.presentB && !r.presentA;
              const removed = r.presentA && !r.presentB;
              return (
                <tr key={r.regionKey} className="hover:bg-surface-1">
                  <Td>
                    <Link className="font-medium text-accent hover:underline" href={linkFor(r.regionKey)}>
                      {r.regionKey}
                    </Link>
                  </Td>
                  <Td><span className="text-text-muted">{r.vendor ?? "—"}</span></Td>
                  <Td numeric><CostCell value={r.monthlyCostUsdA} fallbackRunId={r.fallbackA} /></Td>
                  <Td numeric><CostCell value={r.monthlyCostUsdB} fallbackRunId={r.fallbackB} /></Td>
                  <Td numeric className={deltaTone(r.monthlyCostDelta, true)}>
                    {moneyDelta(r.monthlyCostDelta)}
                  </Td>
                  <Td numeric>{money(r.potentialSavingsA)}</Td>
                  <Td numeric>{money(r.potentialSavingsB)}</Td>
                  <Td><ScenarioCell name={r.bestScenarioA} /></Td>
                  <Td><ScenarioCell name={r.bestScenarioB} /></Td>
                  <Td>
                    {added ? (
                      <Badge tone="info">new</Badge>
                    ) : removed ? (
                      <Badge tone="warn">gone</Badge>
                    ) : null}
                  </Td>
                </tr>
              );
            })}
          </tbody>
        </DataTable>
      )}

      {hasFallback && (
        <p className="text-xs text-text-muted">
          * value pulled from an older run — hover the cost to see which.
        </p>
      )}
    </div>
  );
}
