// §2 cost overview table: the "$price x qty" nodegroup arithmetic, node
// subtotal, vmstorage PVC line and grand total.

import type { CostOverview } from "@/engine/report-model";
import { money, num } from "@/lib/fmt";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

export function CostOverviewTable({ cost }: { cost: CostOverview }) {
  if (cost.nodegroupUnits.length === 0) {
    return <Empty>No priced nodegroups — inventory has no instance types or pricing is missing.</Empty>;
  }
  // nodegroupUnits is already merged per (name, instanceType) by the engine
  // (cross-AZ entries folded), so rows render as delivered.
  const nodeCount = cost.nodegroupUnits.reduce((s, u) => s + u.count, 0);
  return (
    <DataTable>
      <thead>
        <tr>
          <Th>Nodegroup</Th>
          <Th>Instance type</Th>
          <Th numeric>Nodes</Th>
          <Th numeric>Unit price/mo</Th>
          <Th numeric>Cost/mo</Th>
        </tr>
      </thead>
      <tbody>
        {cost.nodegroupUnits.map((u) => (
          <tr key={`${u.name} ${u.instanceType}`} className="hover:bg-surface-1">
            <Td className="font-medium">{u.name}</Td>
            <Td><span className="text-text-muted">{u.instanceType}</span></Td>
            <Td numeric>{num(u.count)}</Td>
            <Td numeric>{money(u.unitPrice)}</Td>
            <Td numeric>{money(u.cost)}</Td>
          </tr>
        ))}
        <tr className="font-medium">
          <Td>Nodes total</Td>
          <Td><span className="text-text-muted">—</span></Td>
          <Td numeric>{num(nodeCount)}</Td>
          <Td numeric><span className="text-text-muted">—</span></Td>
          <Td numeric>{money(cost.nodeCost)}</Td>
        </tr>
        <tr>
          <Td>vmstorage PVCs</Td>
          <Td><span className="text-text-muted">{num(cost.pvcTotalGib)} GiB</span></Td>
          <Td numeric>{num(cost.pvcCount)}</Td>
          <Td numeric>{money(cost.pvcRate, 4)}/GiB</Td>
          <Td numeric>{money(cost.pvcCost)}</Td>
        </tr>
        <tr className="font-medium">
          <Td>Total</Td>
          <Td><span className="text-text-muted">—</span></Td>
          <Td numeric><span className="text-text-muted">—</span></Td>
          <Td numeric><span className="text-text-muted">—</span></Td>
          <Td numeric>{money(cost.total)}</Td>
        </tr>
      </tbody>
    </DataTable>
  );
}
