import { useMemo } from "react";
import {
  Graph,
  type GraphData,
  type GraphNode,
  type GraphLink,
} from "@/modules/graph";
import { useAgentStore } from "@/app/providers/layout/store/agent.store";

const buildGraphFromAgents = (): GraphData => {
  const agents = useAgentStore.getState().agents;
  const nodes: GraphNode[] = [];
  const links: GraphLink[] = [];

  agents.forEach((agent) => {
    // Агент как узел
    nodes.push({
      id: agent.label,
      name: agent.label,
      type: "agent",
      val: 8,
      description: `Агент: ${agent.label}`,
    });

    // Сервисы агента как узлы + связи
    agent.services.forEach((service) => {
      const serviceId = `${agent.label}-${service}`;
      nodes.push({
        id: serviceId,
        name: service,
        type: "service",
        val: 12,
        description: `Сервис: ${service}`,
      });

      links.push({
        source: agent.label,
        target: serviceId,
        type: "hosts",
      });
    });
  });

  return { nodes, links };
};

export const GraphsPage = () => {
  const agents = useAgentStore((s) => s.agents);

  const graphData: GraphData = useMemo(() => {
    return buildGraphFromAgents();
  }, [agents]);

  return (
    <div className="h-full">
      <Graph initialData={graphData} />
    </div>
  );
};
