"use client";

import { useTranslation } from "react-i18next";

import { TableCell, TableHead } from "@/components/ui/table";
import { cn } from "@/lib/utils";

export type AdminAgentFields = {
  agent_node_id?: number | null;
  agent_code?: string | null;
  agent_name?: string | null;
};

function cellText(value: string | null | undefined): string {
  const trimmed = value?.trim() ?? "";
  return trimmed !== "" ? trimmed : "—";
}

export function adminAgentDisplayLabel(row: AdminAgentFields): string {
  const name = row.agent_name?.trim() ?? "";
  const code = row.agent_code?.trim() ?? "";
  if (name !== "" && code !== "") {
    return `${name} · ${code}`;
  }
  return name || code || "—";
}

type HeadProps = { className?: string };
type CellProps = { row: AdminAgentFields; className?: string };

export function AdminAgentHead({ className }: HeadProps): React.ReactElement {
  const { t } = useTranslation("common");
  return (
    <TableHead className={cn("min-w-[7.5rem] whitespace-nowrap", className)}>
      {t("agentColumns.agent")}
    </TableHead>
  );
}

export function AdminAgentCell({ row, className }: CellProps): React.ReactElement {
  const name = cellText(row.agent_name);
  const code = row.agent_code?.trim() ?? "";

  return (
    <TableCell className={cn("min-w-[7.5rem] max-w-[10rem] align-top text-xs", className)}>
      <div className="min-w-0 space-y-0.5">
        <span className="block truncate font-medium" title={name !== "—" ? name : undefined}>
          {name}
        </span>
        {code !== "" ? (
          <span
            className="block truncate font-mono text-[11px] text-muted-foreground"
            title={code}
          >
            {code}
          </span>
        ) : null}
      </div>
    </TableCell>
  );
}

export function AdminAgentIdentityHeads({ className }: { className?: string }): React.ReactElement {
  return <AdminAgentHead className={className} />;
}

export function AdminAgentIdentityCells({ row, className }: CellProps): React.ReactElement {
  return <AdminAgentCell row={row} className={className} />;
}
