// §8 capacity reduction opportunities: nodegroups that could shed nodes or
// are downsize candidates. Rows are filtered to actionable ones — couldRemove
// > 0 or either candidate flag.

import type { ReductionOpportunities as ReductionData } from "@/engine/report-model";
import { num, pct } from "@/lib/fmt";
import { Badge } from "@/components/ui/Badge";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

export function ReductionOpportunities({ data }: { data: ReductionData }) {
  const rows = data.nodegroups.filter(
    (r) => r.couldRemove > 0 || r.reductionCandidate || r.downsizeCandidate,
  );
  if (rows.length === 0) {
    return <Empty>No nodegroup reduction opportunities — capacity matches demand.</Empty>;
  }
  return (
    <DataTable>
      <thead>
        <tr>
          <Th>Nodegroup</Th>
          <Th>Instance type</Th>
          <Th>Capacity</Th>
          <Th numeric>Nodes</Th>
          <Th numeric>Could remove</Th>
          <Th numeric>New util CPU</Th>
          <Th numeric>New util mem</Th>
          <Th>Estimate</Th>
          <Th>Action</Th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r) => (
          <tr key={r.ngName} className="hover:bg-surface-1">
            <Td className="font-medium">{r.ngName}</Td>
            <Td><span className="text-text-muted">{r.instanceType || "—"}</span></Td>
            <Td><span className="text-text-muted">{r.capacityType || "—"}</span></Td>
            <Td numeric>{num(r.count)}</Td>
            <Td numeric className={r.couldRemove > 0 ? "font-medium text-success" : ""}>
              {num(r.couldRemove)}
            </Td>
            <Td numeric>{pct(r.newUtilCpu)}</Td>
            <Td numeric>{pct(r.newUtilMem)}</Td>
            <Td>
              <Badge tone={r.estimateSource === "scenario" ? "info" : "neutral"} title={r.estimateSource === "scenario" ? "from the minimum feasible scenario" : "ratio-based estimate (no feasible scenario)"}>
                {r.estimateSource}
              </Badge>
            </Td>
            <Td>
              {r.reductionCandidate ? <Badge tone="good">reduce</Badge> : null}{" "}
              {r.downsizeCandidate ? <Badge tone="info">downsize</Badge> : null}
            </Td>
          </tr>
        ))}
      </tbody>
    </DataTable>
  );
}
