"use client";

import { useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button, ButtonLink, RefreshButton } from "@/components/ui/Button";
import { parseApiResponse } from "@/lib/api-client";
import { QueryErrorBanner } from "../observe/components/query-error-banner";
import { ObserveViewSwitcher } from "../observe/components/observe-view-switcher";
import { RegionStatusDot } from "../observe/components/region-status-dot";
import type {
  AcsAgentCounts,
  AcsAgentsDetails,
  AcsAgentsOverview,
  AcsAgentsOverviewRegion,
} from "@/lib/observe/agents";

const EMPTY_VALUE_LABEL = "-";
const AGENT_STATUS_TOOLTIP_HEIGHT_PX = 94;
const AGENT_STATUS_TOOLTIP_GAP_PX = 8;

function parseRegionsParam(value: string | null): string[] {
  return (value ?? "")
    .split(",")
    .map((regionId) => regionId.trim())
    .filter(Boolean);
}

function formatCount(value: number | null): string {
  return value === null ? EMPTY_VALUE_LABEL : String(value);
}

function countsTextClass(
  value: number | null,
  kind: "normal" | "hibernated" | "paused" | "specialConfig" | "abnormal"
): string {
  if (value === null) return "text-text-muted";
  if (kind === "normal") return "text-text-primary";
  return value > 0 ? "text-danger" : "text-success";
}

export function resolveAgentStatusTooltipPlacement(
  top: number,
  bottom: number,
  viewportHeight: number
): "above" | "below" {
  const requiredSpace = AGENT_STATUS_TOOLTIP_HEIGHT_PX + AGENT_STATUS_TOOLTIP_GAP_PX;
  const aboveSpace = top;
  const belowSpace = Math.max(0, viewportHeight - bottom);

  if (aboveSpace < requiredSpace && belowSpace >= requiredSpace) return "below";
  if (belowSpace < requiredSpace && aboveSpace >= requiredSpace) return "above";
  return aboveSpace >= belowSpace ? "above" : "below";
}

function statusClass(status: string | null): string {
  if (!status) return "bg-surface-1 text-text-muted border-surface-2/60";
  if (status === "Normal") return "bg-success/12 text-success border-success/30";
  if (status === "Hibernated") return "bg-warning/12 text-warning border-warning/30";
  if (status === "Deleting") return "bg-danger/12 text-danger border-danger/30";
  return "bg-sky-500/10 text-sky-500 border-sky-500/30";
}

function pauseLabel(value: string | null): string {
  if (value === "true") return "Paused";
  return value ?? EMPTY_VALUE_LABEL;
}

function pauseClass(value: string | null): string {
  if (value === "true") return "bg-warning/12 text-warning border-warning/30";
  if (!value) return "bg-surface-1 text-text-muted border-surface-2/60";
  return "bg-text-muted/12 text-text-secondary border-surface-2";
}

export function formatAgentAge(createdAtUnixSeconds: number): string {
  const elapsedSeconds = Math.max(0, Math.floor(Date.now() / 1000) - createdAtUnixSeconds);
  if (elapsedSeconds < 60) return `${elapsedSeconds}s`;
  const elapsedMinutes = Math.floor(elapsedSeconds / 60);
  if (elapsedMinutes < 60) return `${elapsedMinutes}m`;
  const elapsedHours = Math.floor(elapsedMinutes / 60);
  if (elapsedHours < 24) return `${elapsedHours}h`;
  const elapsedDays = Math.floor(elapsedHours / 24);
  if (elapsedDays < 365) return `${elapsedDays}d`;
  return `${Math.floor(elapsedDays / 365)}y`;
}

function regionMetaLabel(region: AcsAgentsOverviewRegion): string {
  return `${region.architecture}/${region.environment}/${region.provider}`;
}

function agentBadgeClass(agent: string): string {
  const base = "inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium";
  const classes: Record<string, string> = {
    o11yk8s: "border-blue-500/30 bg-blue-500/10 text-blue-400",
    o11ytidb: "border-purple-500/30 bg-purple-500/10 text-purple-400",
    kubernetes: "border-indigo-500/30 bg-indigo-500/10 text-indigo-400",
    sharedpool: "border-rose-500/30 bg-rose-500/10 text-rose-400",
    tidbgroup: "border-cyan-500/30 bg-cyan-500/10 text-cyan-400",
  };

  return `${base} ${classes[agent] ?? "border-surface-2 bg-text-muted/12 text-text-secondary"}`;
}

function AgentsPageContent() {
  const searchParams = useSearchParams();
  const selectedRegionIds = useMemo(
    () => parseRegionsParam(searchParams.get("regions")),
    [searchParams]
  );
  const [overview, setOverview] = useState<AcsAgentsOverview | null>(null);
  const [overviewLoading, setOverviewLoading] = useState(selectedRegionIds.length > 0);
  const [overviewError, setOverviewError] = useState("");
  const [detailsByRegion, setDetailsByRegion] = useState<Record<string, AcsAgentsDetails>>({});
  const [detailsLoadingRegionId, setDetailsLoadingRegionId] = useState<string | null>(null);
  const [expandedRegionIds, setExpandedRegionIds] = useState<Set<string>>(new Set());

  const loadOverview = useCallback(() => {
    if (selectedRegionIds.length === 0) {
      setOverview(null);
      return;
    }

    setOverviewLoading(true);
    setOverviewError("");
    fetch("/api/observe/acs/agents-overview", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ regionIds: selectedRegionIds }),
    })
      .then((res) => parseApiResponse<AcsAgentsOverview>(res))
      .then((payload) => {
        if (payload.ok) {
          setOverview(payload.data);
        } else {
          setOverviewError(payload.error.message);
        }
      })
      .catch((e) => setOverviewError((e as Error).message))
      .finally(() => setOverviewLoading(false));
  }, [selectedRegionIds]);

  const loadDetails = useCallback((regionId: string, force = false) => {
    if (!force && detailsByRegion[regionId]) return;

    setDetailsLoadingRegionId(regionId);
    fetch("/api/observe/acs/agents-details", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ regionId }),
    })
      .then((res) => parseApiResponse<AcsAgentsDetails>(res))
      .then((payload) => {
        if (payload.ok) {
          setDetailsByRegion((current) => ({
            ...current,
            [regionId]: payload.data,
          }));
        }
      })
      .finally(() => setDetailsLoadingRegionId(null));
  }, [detailsByRegion]);

  useEffect(() => {
    loadOverview();
  }, [loadOverview]);

  const toggleRegion = (regionId: string) => {
    setExpandedRegionIds((current) => {
      const next = new Set(current);
      if (next.has(regionId)) {
        next.delete(regionId);
      } else {
        next.add(regionId);
        loadDetails(regionId);
      }
      return next;
    });
  };

  if (selectedRegionIds.length === 0) {
    return (
      <div className="space-y-6 animate-fade-in">
        <section className="flex items-start justify-between gap-4">
          <h2 className="text-xl font-semibold tracking-tight">Agents</h2>
        </section>
        <section className="bg-surface-0 border border-surface-2 rounded-lg p-6 max-w-lg">
          <h3 className="text-lg font-semibold">Select regions first</h3>
          <p className="mt-2 text-sm text-text-secondary">
            Choose regions on the Regions page, then return to this workflow.
          </p>
          <ButtonLink
            href="/regions"
            size="sm"
            className="mt-4"
          >
            Go to Regions
          </ButtonLink>
        </section>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <section className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-xl font-semibold tracking-tight">Agents</h2>
        </div>
        <ObserveViewSwitcher activeView="agents" regionIds={selectedRegionIds} />
      </section>

      <QueryErrorBanner title="Failed to load Agents" message={overviewError} />

      {overview && (
        <section className="space-y-4">
          <div className="flex items-center justify-between gap-4">
            <p className="text-sm text-text-secondary" data-testid="agents-coverage">
              <span className="font-medium text-text-primary">{overview.coverage.selected}</span>{" "}
              selected · <span className="font-medium text-success">{overview.coverage.ready}</span>{" "}
              ready · <span className="font-medium text-text-primary">{overview.coverage.totalAgents}</span>{" "}
              agents
            </p>
            <RefreshButton
              aria-label="Refresh Agents"
              onClick={() => loadOverview()}
              disabled={overviewLoading}
              busy={overviewLoading}
            />
          </div>

          <section className="bg-surface-0 border border-surface-2 rounded-lg overflow-x-auto">
            <table className="w-full min-w-[56rem] text-sm">
              <thead>
                <tr className="border-b border-surface-2">
                  <th className="w-60 px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                    Region
                  </th>
                  {overview.agentTypes.map((agentType) => (
                    <th
                      key={agentType.agent}
                      className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted"
                    >
                      {agentType.agent}
                    </th>
                  ))}
                  <th className="pl-6 pr-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                    Agent details
                  </th>
                </tr>
              </thead>
              <tbody>
                {overview.regions.map((region) => (
                  <RegionOverviewRow
                    key={region.regionId}
                    region={region}
                    details={detailsByRegion[region.regionId]}
                    expanded={expandedRegionIds.has(region.regionId)}
                    loading={detailsLoadingRegionId === region.regionId}
                    agentTypes={overview.agentTypes.map((item) => item.agent)}
                    onToggle={() => toggleRegion(region.regionId)}
                    onRefresh={() => loadDetails(region.regionId, true)}
                  />
                ))}
              </tbody>
            </table>
          </section>
        </section>
      )}
    </div>
  );
}

function AgentsPageSkeleton() {
  return (
    <div className="space-y-6 animate-fade-in">
      <section className="flex items-start justify-between gap-4">
        <h2 className="text-xl font-semibold tracking-tight">Agents</h2>
      </section>
      <section className="bg-surface-0 border border-surface-2 rounded-lg p-6 max-w-2xl">
        <div className="h-5 w-32 rounded bg-surface-2" />
        <div className="mt-3 h-4 w-72 max-w-full rounded bg-surface-2/70" />
      </section>
    </div>
  );
}

export default function AgentsPage() {
  return (
    <Suspense fallback={<AgentsPageSkeleton />}>
      <AgentsPageContent />
    </Suspense>
  );
}

function RegionOverviewRow({
  region,
  details,
  expanded,
  loading,
  agentTypes,
  onToggle,
  onRefresh,
}: {
  region: AcsAgentsOverviewRegion;
  details?: AcsAgentsDetails;
  expanded: boolean;
  loading: boolean;
  agentTypes: string[];
  onToggle: () => void;
  onRefresh: () => void;
}) {
  return (
    <>
      <tr className="border-b border-surface-2/50 hover:bg-surface-1 transition-colors">
        <td className="px-4 py-2.5">
          <div className="flex items-center gap-2 font-medium">
            <span>{region.regionName}</span>
            <RegionStatusDot
              status={region.status}
              errorMessage={region.errorMessage}
              fallbackErrorMessage="Prometheus query failed"
            />
          </div>
          <div className="text-xs text-text-muted">{regionMetaLabel(region)}</div>
        </td>
        {agentTypes.map((agentType) => (
          <td key={agentType} className="px-4 py-2.5">
            <AgentTypeStatusCell counts={region.byAgentType[agentType]} />
          </td>
        ))}
        <td className="pl-6 pr-4 py-2.5">
          <Button
            type="button"
            aria-expanded={expanded}
            aria-label={expanded ? `Hide details for ${region.regionName}` : `Show details for ${region.regionName}`}
            onClick={onToggle}
            variant="subtle"
            size="xs"
          >
            {expanded ? "Hide details" : "Show details"}
          </Button>
        </td>
      </tr>
      {expanded && (
        <tr className="border-b border-surface-2/50 bg-surface-1/40">
          <td colSpan={agentTypes.length + 2} className="px-4 py-3">
            <AgentDetailsPanel
              regionName={region.regionName}
              details={details}
              loading={loading}
              onRefresh={onRefresh}
            />
          </td>
        </tr>
      )}
    </>
  );
}

function AgentTypeStatusCell({ counts }: { counts?: AcsAgentCounts }) {
  const [hovered, setHovered] = useState(false);
  const [tooltipPlacement, setTooltipPlacement] = useState<"above" | "below">("above");
  const [tooltipPosition, setTooltipPosition] = useState({ left: 0, top: 0 });

  if (!counts) {
    return <span className="font-mono text-[13px] text-text-muted">{EMPTY_VALUE_LABEL}</span>;
  }

  return (
    <div
      className="relative inline-flex flex-wrap items-center gap-1.5 font-mono text-[12px]"
      onMouseEnter={(event) => {
        const { left, right, top, bottom } = event.currentTarget.getBoundingClientRect();
        const nextPlacement = resolveAgentStatusTooltipPlacement(top, bottom, window.innerHeight);
        setTooltipPlacement(nextPlacement);
        setTooltipPosition({
          left: (left + right) / 2,
          top:
            nextPlacement === "above"
              ? top - AGENT_STATUS_TOOLTIP_GAP_PX
              : bottom + AGENT_STATUS_TOOLTIP_GAP_PX,
        });
        setHovered(true);
      }}
      onMouseLeave={() => setHovered(false)}
    >
      <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-surface-2/60 bg-surface-1 px-1 py-0.5">
        <span className="text-[10px] text-text-muted">N:</span>
        <span className={countsTextClass(counts.normal, "normal")}>{formatCount(counts.normal)}</span>
      </span>
      <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-warning/20 bg-warning-muted px-1 py-0.5">
        <span className="text-[10px] text-text-muted">H:</span>
        <span className={countsTextClass(counts.hibernated, "hibernated")}>{formatCount(counts.hibernated)}</span>
      </span>
      <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-arch-dedicated/20 bg-arch-dedicated/10 px-1 py-0.5">
        <span className="text-[10px] text-text-muted">P:</span>
        <span className={countsTextClass(counts.paused, "paused")}>{formatCount(counts.paused)}</span>
      </span>
      <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-danger/20 bg-danger-muted px-1 py-0.5">
        <span className="text-[10px] text-text-muted">A:</span>
        <span className={countsTextClass(counts.abnormal, "abnormal")}>{formatCount(counts.abnormal)}</span>
      </span>
      <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-accent/20 bg-accent/10 px-1 py-0.5">
        <span className="text-[10px] text-text-muted">S:</span>
        <span className={countsTextClass(counts.specialConfig, "specialConfig")}>
          {formatCount(counts.specialConfig)}
        </span>
      </span>
      {hovered ? (
        <span
          role="tooltip"
          style={{ left: tooltipPosition.left, top: tooltipPosition.top }}
          className={`pointer-events-none fixed z-50 -translate-x-1/2 rounded-lg border border-surface-2 bg-surface-0/95 px-2.5 py-2 text-[11px] text-text-primary shadow-xl backdrop-blur-sm ${tooltipPlacement === "above" ? "-translate-y-full" : ""}`}
        >
          <span className="grid gap-1 whitespace-nowrap">
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-text-secondary" />
              {`Normal: ${counts.normal ?? EMPTY_VALUE_LABEL}`}
            </span>
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-warning" />
              {`Hibernated: ${counts.hibernated ?? EMPTY_VALUE_LABEL}`}
            </span>
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-danger" />
              {`Paused: ${counts.paused ?? EMPTY_VALUE_LABEL}`}
            </span>
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-accent" />
              {`SpecialConfig: ${counts.specialConfig ?? EMPTY_VALUE_LABEL}`}
            </span>
            <span className="inline-flex items-center gap-1.5">
              <span className="h-1.5 w-1.5 rounded-full bg-danger" />
              {`Abnormal: ${counts.abnormal ?? EMPTY_VALUE_LABEL}`}
            </span>
          </span>
        </span>
      ) : null}
    </div>
  );
}

function TemplatePathCell({ value }: { value: string | null }) {
  const label = value ?? EMPTY_VALUE_LABEL;

  return (
    <td className="px-3 py-2 font-mono text-[13px] text-text-secondary">
      <span
        title={value ?? undefined}
        className="inline-block max-w-[12rem] truncate overflow-hidden whitespace-nowrap align-bottom"
      >
        {label}
      </span>
    </td>
  );
}

function AgentAgeCell({ createdAtUnixSeconds }: { createdAtUnixSeconds: number | null }) {
  if (!createdAtUnixSeconds || createdAtUnixSeconds <= 0) {
    return (
      <td className="px-3 py-2 font-mono text-[13px] text-text-muted">
        {EMPTY_VALUE_LABEL}
      </td>
    );
  }

  const createdAtIso = new Date(createdAtUnixSeconds * 1000).toISOString();

  return (
    <td className="px-3 py-2 font-mono text-[13px] text-text-secondary">
      <time
        dateTime={createdAtIso}
        title={createdAtIso}
      >
        {formatAgentAge(createdAtUnixSeconds)}
      </time>
    </td>
  );
}

function agentStatusFilterKey(status: string | null): string {
  return status ?? EMPTY_VALUE_LABEL;
}

function agentHasSpecialConfig(agent: { vmagentConfigTemplate: string | null; vectorConfigTemplate: string | null }) {
  return Boolean(agent.vmagentConfigTemplate || agent.vectorConfigTemplate);
}

function AgentDetailsPanel({
  regionName,
  details,
  loading,
  onRefresh,
}: {
  regionName: string;
  details?: AcsAgentsDetails;
  loading: boolean;
  onRefresh: () => void;
}) {
  const agents = useMemo(() => details?.agents ?? [], [details]);
  const [selectedStatuses, setSelectedStatuses] = useState<Set<string>>(new Set());
  const [specialConfigOnly, setSpecialConfigOnly] = useState(false);
  const [statusFilterOpen, setStatusFilterOpen] = useState(false);
  const statusFilterRef = useRef<HTMLDivElement>(null);
  const statusOptions = useMemo(() => {
    const counts = new Map<string, number>();
    for (const agent of agents) {
      const status = agentStatusFilterKey(agent.status);
      counts.set(status, (counts.get(status) ?? 0) + 1);
    }

    return [...counts.entries()]
      .map(([status, count]) => ({ status, count }))
      .sort((a, b) => a.status.localeCompare(b.status));
  }, [agents]);
  const availableStatuses = useMemo(
    () => new Set(statusOptions.map((option) => option.status)),
    [statusOptions]
  );
  const visibleAgents = useMemo(() => {
    return agents.filter((agent) => {
      if (selectedStatuses.size > 0 && !selectedStatuses.has(agentStatusFilterKey(agent.status))) {
        return false;
      }
      return !specialConfigOnly || agentHasSpecialConfig(agent);
    });
  }, [agents, selectedStatuses, specialConfigOnly]);

  useEffect(() => {
    setSelectedStatuses((current) => {
      const next = new Set([...current].filter((status) => availableStatuses.has(status)));
      return next.size === current.size ? current : next;
    });
  }, [availableStatuses]);

  useEffect(() => {
    if (!statusFilterOpen) return;

    const onPointerDown = (event: PointerEvent) => {
      const target = event.target;
      if (!(target instanceof Node) || !statusFilterRef.current?.contains(target)) {
        setStatusFilterOpen(false);
      }
    };

    document.addEventListener("pointerdown", onPointerDown, { capture: true });
    return () => document.removeEventListener("pointerdown", onPointerDown, { capture: true });
  }, [statusFilterOpen]);

  const toggleStatus = (status: string) => {
    setSelectedStatuses((current) => {
      const next = new Set(current);
      if (next.has(status)) {
        next.delete(status);
      } else {
        next.add(status);
      }
      return next;
    });
  };

  return (
    <div className="rounded-lg border border-surface-2 bg-surface-0">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-surface-2 px-3 py-3">
        <div>
          <h3 className="text-sm font-semibold text-text-primary">{regionName} agents</h3>
        </div>
        <div className="flex items-center gap-2">
          <label className="inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-surface-2 bg-surface-1 px-2.5 py-1 text-xs font-medium text-text-secondary transition-colors hover:border-accent/30 hover:text-text-primary">
            <input
              type="checkbox"
              checked={specialConfigOnly}
              onChange={(event) => setSpecialConfigOnly(event.target.checked)}
              aria-label="Show SpecialConfig Only"
              className="h-3.5 w-3.5 accent-accent"
            />
            <span>SpecialConfig Only</span>
          </label>
          <div ref={statusFilterRef} className="relative">
            <Button
              type="button"
              aria-expanded={statusFilterOpen}
              onClick={() => setStatusFilterOpen((open) => !open)}
              variant="secondary"
              size="xs"
            >
              {selectedStatuses.size === 0 ? "Status: All" : `Status: ${selectedStatuses.size} selected`}
            </Button>
            {statusFilterOpen ? (
              <div className="absolute right-0 z-20 mt-2 min-w-44 rounded-lg border border-surface-2 bg-surface-0 p-2 shadow-xl">
                <div className="grid gap-1">
                  {statusOptions.map((option) => (
                    <label
                      key={option.status}
                      className="flex cursor-pointer items-center justify-between gap-3 rounded-md px-2 py-1 text-xs text-text-secondary hover:bg-surface-1"
                    >
                      <span className="inline-flex items-center gap-2">
                        <input
                          type="checkbox"
                          checked={selectedStatuses.has(option.status)}
                          onChange={() => toggleStatus(option.status)}
                          aria-label={`Filter status ${option.status}`}
                          className="h-3.5 w-3.5 accent-accent"
                        />
                        <span className="font-mono">{option.status}</span>
                      </span>
                      <span className="font-mono text-text-muted">{option.count}</span>
                    </label>
                  ))}
                </div>
                <div className="mt-2 border-t border-surface-2 pt-2">
                  <Button
                    type="button"
                    onClick={() => {
                      setSelectedStatuses(new Set());
                      setStatusFilterOpen(false);
                    }}
                    disabled={selectedStatuses.size === 0}
                    aria-label="Clear status filter"
                    variant="plain"
                    size="xs"
                    className="w-full justify-start"
                  >
                    Clear
                  </Button>
                </div>
              </div>
            ) : null}
          </div>
          <RefreshButton
            aria-label="Refresh"
            onClick={onRefresh}
            disabled={loading}
            busy={loading}
            size="xs"
          />
        </div>
      </div>
      {loading && !details ? (
        <div className="px-3 py-4 text-sm text-text-muted">Loading agent details...</div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full min-w-[76rem] text-sm">
            <thead>
              <tr className="border-b border-surface-2">
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Agent
                </th>
                <th className="w-px pl-3 pr-14 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted whitespace-nowrap">
                  K8s Cluster
                </th>
                <th className="pl-2 pr-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Tenant
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Application
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Age
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Status
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Pause
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  VMagent Template
                </th>
                <th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                  Vector Template
                </th>
              </tr>
            </thead>
            <tbody>
              {agents.length === 0 ? (
                <tr>
                  <td colSpan={9} className="px-3 py-3 text-sm text-text-muted">
                    No agents found.
                  </td>
                </tr>
              ) : visibleAgents.length === 0 ? (
                <tr>
                  <td colSpan={9} className="px-3 py-3 text-sm text-text-muted">
                    No agents match the selected filters.
                  </td>
                </tr>
              ) : (
                visibleAgents.map((agent) => (
                  <tr key={agent.key} className="border-b border-surface-2/50 last:border-0">
                    <td className="px-3 py-2 font-mono text-[13px] text-text-secondary">
                      <span className={agentBadgeClass(agent.agent)}>
                        {agent.agent}
                      </span>
                    </td>
                    <td className="w-px pl-3 pr-14 py-2 font-mono text-[13px] text-text-secondary whitespace-nowrap">
                      {agent.k8sClusterName}
                    </td>
                    <td className="pl-2 pr-3 py-2 font-mono text-[13px] text-text-secondary">
                      {agent.tenantId}
                    </td>
                    <td className="px-3 py-2 font-mono text-[13px] text-text-secondary">
                      {agent.applicationId}
                    </td>
                    <AgentAgeCell createdAtUnixSeconds={agent.createdAtUnixSeconds} />
                    <td className="px-3 py-2 font-mono text-[13px]">
                      <span
                        className={`inline-flex min-w-[5rem] items-center justify-center rounded-md border px-1.5 py-0.5 text-[12px] font-normal ${statusClass(agent.status)}`}
                      >
                        {agent.status ?? EMPTY_VALUE_LABEL}
                      </span>
                    </td>
                    <td className="px-3 py-2 font-mono text-[13px]">
                      <span
                        className={`inline-flex min-w-[4rem] items-center justify-center rounded-md border px-1.5 py-0.5 text-[12px] font-normal ${pauseClass(agent.pauseReconciliation)}`}
                      >
                        {pauseLabel(agent.pauseReconciliation)}
                      </span>
                    </td>
                    <TemplatePathCell value={agent.vmagentConfigTemplate} />
                    <TemplatePathCell value={agent.vectorConfigTemplate} />
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
