import { useEffect, useState } from "react";
import { Link } from "@/lib/router";
import { useQuery } from "@tanstack/react-query";
import { agentsApi, type OrgNode } from "../api/agents";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { StatusBadge } from "../components/StatusBadge";
import { EmptyState } from "../components/EmptyState";
import { PageSkeleton } from "../components/PageSkeleton";
import { QueryErrorState, useQueryView } from "../components/QueryView";
import { ChevronRight, GitBranch } from "lucide-react";
import { cn } from "../lib/utils";
import { agentStatusDot, agentStatusDotDefault } from "../lib/status-colors";
function OrgTree({
nodes,
depth = 0,
hrefFn,
}: {
nodes: OrgNode[];
depth?: number;
hrefFn: (id: string) => string;
}) {
return (
{nodes.map((node) => (
))}
);
}
function OrgTreeNode({
node,
depth,
hrefFn,
}: {
node: OrgNode;
depth: number;
hrefFn: (id: string) => string;
}) {
const [expanded, setExpanded] = useState(true);
const hasChildren = node.reports.length > 0;
return (
{hasChildren ? (
) : (
)}
{node.name}
{node.role}
{hasChildren && expanded && (
)}
);
}
export function Org() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
useEffect(() => {
setBreadcrumbs([{ label: "Org Chart" }]);
}, [setBreadcrumbs]);
const orgQuery = useQuery({
queryKey: queryKeys.org(selectedCompanyId!),
queryFn: () => agentsApi.org(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const { data, isLoading } = orgQuery;
const orgView = useQueryView(orgQuery);
if (!selectedCompanyId) {
return ;
}
// Keep a loaded chart on screen through a failed refetch; only a real
// failure, or an outage before the first load, replaces the page.
if (isLoading || orgView.kind === "reconnecting") {
return ;
}
if (orgView.kind === "error") {
return (
);
}
return (
{data && data.length === 0 && (
)}
{data && data.length > 0 && (
`/agents/${id}`} />
)}
);
}