import { useRef } from "react";
import { ArrowRight, Database } from "lucide-react";
import { Handle, Position, type NodeProps } from "@xyflow/react";
import type { CanvasNodeData } from "@/lib/layout";
import { SourceComparisonButton } from "@/components/flow/SourceComparisonButton";
import { useRetrievalHoverPreview } from "@/components/flow/RetrievalHoverPreview";

export function DirectToolGroupCard({ data }: NodeProps) {
  const node = data as unknown as CanvasNodeData;
  const item = node.item;
  if (!item || item.itemType !== "retrieval-direct") return null;
  return <DirectToolGroupCardContent node={node} item={item} />;
}

function DirectToolGroupCardContent({ node, item }: { node: CanvasNodeData; item: Extract<NonNullable<CanvasNodeData["item"]>, { itemType: "retrieval-direct" }> }) {
  const cardRef = useRef<HTMLElement>(null);
  const hoverPreview = useRetrievalHoverPreview({ anchorRef: cardRef, buildId: node.buildId, item, onOpenDetail: () => node.onOpen(item, "business") });
  const sourceText = item.group.sources.map((source) => source.businessLabel).join("、") || "相关信息";
  return <><article ref={cardRef} className="flowCard retrievalCard directToolCard" tabIndex={0} data-focus-return={`${item.id}:card`} {...hoverPreview.anchorProps} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); node.onOpen(item, "business"); } }}>
    <Handle type="target" position={Position.Left} className="flowHandle" />
    <Handle type="source" position={Position.Right} className="flowHandle" />
    <header><span className="retrievalKind"><Database size={14} />工具取数</span><span className="retrievalOwner">实现 Agent 直接读取</span></header>
    <h3>{sourceText}</h3>
    <dl className="retrievalStats"><div><dt>读取</dt><dd>{item.group.callCount} 次</dd></div><div><dt>结果</dt><dd>{item.group.failureCount ? `${item.group.failureCount} 次失败` : item.group.interruptedCount ? `${item.group.interruptedCount} 次中断` : item.group.runningCount ? "进行中" : "已完成"}</dd></div></dl>
    <footer><button type="button" className="nodeAction nodrag nopan" data-focus-return={`${item.id}:business`} onClick={(event) => { event.stopPropagation(); node.onOpen(item, "business"); }}>查看读取内容<ArrowRight size={14} /></button><SourceComparisonButton item={item} onOpen={node.onOpen} /></footer>
  </article>{hoverPreview.preview}</>;
}
