// §6 per-node request distribution: requested cpu/mem vs allocatable per
// node, beside the run-collected 7d-max actual usage. Pressure above 85%
// is conveyed by the util bars alone — no whole-row tint. podCount counts
// non-DaemonSet workload pods only — on VM clusters most nodes are
// vmstorage anti-affinity hosts carrying exactly one.
// Rows are click-to-expand (same interaction as the workload table): the
// expanded row reveals the node's live utilization chart.

import { Fragment, useState } from "react";
import type { PerNodeDistributionRow } from "@/engine/report-model";
import { num, fixed } from "@/lib/fmt";
import { DataTable, Td, Th, rowKeyActivate } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";
import { UtilBar } from "@/components/ui/UtilBar";
import { NodeUsageChart } from "@/components/regions/NodeUsageChart";

const COLS = 11;

export function PerNodeDistribution({
  rows,
  regionKey,
}: {
  rows: PerNodeDistributionRow[];
  regionKey: string;
}) {
  const [expanded, setExpanded] = useState<string | null>(null);
  if (rows.length === 0) {
    return <Empty>No per-node distribution — inventory collected no nodes.</Empty>;
  }
  return (
    <DataTable>
      <thead>
        <tr>
          <Th>Node</Th>
          <Th>Nodegroup</Th>
          <Th numeric>Non-DS pods</Th>
          <Th numeric>Req CPU</Th>
          <Th>vs allocatable</Th>
          <Th numeric>Req mem</Th>
          <Th>vs allocatable</Th>
          <Th
            numeric
            title="Max actual CPU usage over the run's lookback window, collected at run time"
          >
            Max CPU
          </Th>
          <Th title="Max CPU usage as a share of allocatable">vs allocatable</Th>
          <Th
            numeric
            title="Max actual working-set memory over the run's lookback window, collected at run time"
          >
            Max mem
          </Th>
          <Th title="Max memory usage as a share of allocatable">vs allocatable</Th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r) => {
          return (
            <Fragment key={r.node}>
              <tr
                onClick={() => setExpanded((cur) => (cur === r.node ? null : r.node))}
                onKeyDown={rowKeyActivate(() => setExpanded((cur) => (cur === r.node ? null : r.node)))}
                tabIndex={0}
                className={`cursor-pointer hover:bg-surface-1 ${expanded === r.node ? "bg-surface-1" : ""}`}
              >
                <Td className="font-medium">{r.node}</Td>
                <Td><span className="text-text-muted">{r.nodegroup || "—"}</span></Td>
                <Td numeric>{num(r.podCount)}</Td>
                <Td numeric>{fixed(r.reqCpu)} cores</Td>
                <Td><UtilBar value={r.pctC} label="requested CPU vs allocatable" /></Td>
                <Td numeric>{fixed(r.reqMemGib)} GiB</Td>
                <Td><UtilBar value={r.pctM} label="requested memory vs allocatable" /></Td>
                <Td numeric>{r.maxCpuCores == null ? "—" : `${fixed(r.maxCpuCores)} cores`}</Td>
                <Td><UtilBar value={r.maxPctC ?? null} label="max CPU vs allocatable" /></Td>
                <Td numeric>{r.maxMemGib == null ? "—" : `${fixed(r.maxMemGib)} GiB`}</Td>
                <Td><UtilBar value={r.maxPctM ?? null} label="max memory vs allocatable" /></Td>
              </tr>
              {expanded === r.node ? (
                <tr>
                  <td colSpan={COLS} className="border-b border-surface-2/50 bg-surface-1/50 px-4 py-3">
                    <NodeUsageChart
                      regionKey={regionKey}
                      node={r.node}
                      allocatableCpu={r.allocatableCpu}
                      allocatableMemGib={r.allocatableMemGib}
                    />
                  </td>
                </tr>
              ) : null}
            </Fragment>
          );
        })}
      </tbody>
    </DataTable>
  );
}
