// Attention list: the dashboard's verdict surface. Merges four signals
// into one ranked list — pricing-missing regions first (their numbers are
// placeholders), then the top-5 savings opportunities, then the top-3
// WoW cost increases. One row per region (highest-priority signal wins),
// capped at 8 rows; idle/overprovisioned counts ride along as badges.

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

export type AttentionPrimary = "pricing" | "savings" | "wow";

export interface AttentionRow {
  region: RegionOverviewRow;
  primary: AttentionPrimary;
  badges: Array<{ label: string; tone: "warn" | "good" | "bad" | "neutral"; title?: string }>;
}

/** Derive the ranked attention rows (exported for tests). */
export function attentionRows(regions: RegionOverviewRow[]): AttentionRow[] {
  const order: string[] = [];
  const byKey = new Map<string, { region: RegionOverviewRow; primary: AttentionPrimary }>();

  const add = (r: RegionOverviewRow, primary: AttentionPrimary): void => {
    if (!byKey.has(r.regionKey)) {
      order.push(r.regionKey);
      byKey.set(r.regionKey, { region: r, primary });
    }
  };

  regions
    .filter((r) => r.pricingMissing)
    .sort((a, b) => (b.monthlyCostUsd ?? 0) - (a.monthlyCostUsd ?? 0))
    .forEach((r) => add(r, "pricing"));

  regions
    .filter((r) => (r.potentialMonthlySavingsUsd ?? 0) > 0)
    .sort((a, b) => (b.potentialMonthlySavingsUsd ?? 0) - (a.potentialMonthlySavingsUsd ?? 0))
    .slice(0, 5)
    .forEach((r) => add(r, "savings"));

  regions
    .filter((r) => (r.deltaMonthlyCostUsd ?? 0) > 0)
    .sort((a, b) => (b.deltaMonthlyCostUsd ?? 0) - (a.deltaMonthlyCostUsd ?? 0))
    .slice(0, 3)
    .forEach((r) => add(r, "wow"));

  return order.slice(0, 8).map((key) => {
    const { region: r, primary } = byKey.get(key)!;
    const badges: AttentionRow["badges"] = [];
    if (r.pricingMissing) {
      badges.push({
        label: "pricing missing",
        tone: "warn",
        title: (r.pricingMissingTypes ?? []).join(", "),
      });
    }
    if ((r.potentialMonthlySavingsUsd ?? 0) > 0) {
      badges.push({ label: `save ${money(r.potentialMonthlySavingsUsd, 0)}/mo`, tone: "good" });
    }
    if ((r.deltaMonthlyCostUsd ?? 0) > 0) {
      badges.push({ label: `${moneyDelta(r.deltaMonthlyCostUsd)}/mo WoW`, tone: "bad" });
    }
    if ((r.idleCount ?? 0) > 0) {
      badges.push({ label: `${r.idleCount} idle`, tone: "neutral" });
    }
    if ((r.overprovisionedCount ?? 0) > 0) {
      badges.push({ label: `${r.overprovisionedCount} overprovisioned`, tone: "neutral" });
    }
    return { region: r, primary, badges };
  });
}

export function AttentionList({ regions }: { regions: RegionOverviewRow[] }) {
  const rows = attentionRows(regions);

  return (
    <Section
      title="Attention"
      subtitle="pricing gaps, biggest savings opportunities, and WoW cost spikes"
      actions={
        <ButtonLink href="/regions" variant="subtle" size="sm">
          All regions →
        </ButtonLink>
      }
    >
      {rows.length === 0 ? (
        <Empty>Nothing flagged — the fleet looks healthy this week.</Empty>
      ) : (
        <DataTable>
          <thead>
            <tr>
              <Th>Region</Th>
              <Th>Signals</Th>
              <Th numeric>Cost/mo</Th>
              <Th numeric>Δ WoW</Th>
            </tr>
          </thead>
          <tbody>
            {rows.map(({ region: r, badges }) => (
              <tr key={r.regionKey} className="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="flex flex-wrap gap-1">
                    {badges.map((b) => (
                      <Badge key={b.label} tone={b.tone} title={b.title}>
                        {b.label}
                      </Badge>
                    ))}
                  </span>
                </Td>
                <Td numeric>{money(r.monthlyCostUsd)}</Td>
                <Td numeric className={deltaTone(r.deltaMonthlyCostUsd, true)}>
                  {moneyDelta(r.deltaMonthlyCostUsd)}
                </Td>
              </tr>
            ))}
          </tbody>
        </DataTable>
      )}
    </Section>
  );
}
