// Workload diff for the region compare: added/removed keys as colored
// lists, changed workloads as one row per field with its A → B values.

import type { ChangedValue, RegionDiff } from "@/lib/api-types";
import { DataTable, Td, Th } from "@/components/ui/DataTable";
import { Empty } from "@/components/ui/Empty";

/** Numbers with thousands separators, strings as-is. */
export function fmtChangedValue(v: ChangedValue): string {
  return typeof v === "number" ? v.toLocaleString("en-US") : v;
}

export function WorkloadDiff({ workloads }: { workloads: RegionDiff["workloads"] }) {
  const { added, removed, changed } = workloads;
  if (added.length === 0 && removed.length === 0 && changed.length === 0) {
    return <Empty>No workload changes between the two runs.</Empty>;
  }
  return (
    <div className="space-y-4">
      {added.length > 0 && (
        <div>
          <h3 className="text-xs font-medium uppercase tracking-wide text-text-muted">Added</h3>
          <ul className="mt-1 space-y-0.5">
            {added.map((key) => (
              <li key={key} className="font-mono text-xs text-success">
                + {key}
              </li>
            ))}
          </ul>
        </div>
      )}

      {removed.length > 0 && (
        <div>
          <h3 className="text-xs font-medium uppercase tracking-wide text-text-muted">Removed</h3>
          <ul className="mt-1 space-y-0.5">
            {removed.map((key) => (
              <li key={key} className="font-mono text-xs text-danger">
                − {key}
              </li>
            ))}
          </ul>
        </div>
      )}

      {changed.length > 0 && (
        <div>
          <h3 className="text-xs font-medium uppercase tracking-wide text-text-muted">Changed</h3>
          <DataTable>
            <thead>
              <tr>
                <Th>Workload</Th>
                <Th>Field</Th>
                <Th>A → B</Th>
              </tr>
            </thead>
            <tbody>
              {changed.flatMap((row) =>
                row.fields.map((f) => (
                  <tr key={`${row.key}/${f.field}`} className="hover:bg-surface-1">
                    <Td><span className="font-mono text-xs text-text-secondary">{row.key}</span></Td>
                    <Td><span className="font-mono text-xs">{f.field}</span></Td>
                    <Td>
                      <span className="font-mono text-xs text-text-secondary">
                        {fmtChangedValue(f.a)} → {fmtChangedValue(f.b)}
                      </span>
                    </Td>
                  </tr>
                )),
              )}
            </tbody>
          </DataTable>
        </div>
      )}
    </div>
  );
}
