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

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

function RetrievalAgentCardContent({ node, item }: { node: CanvasNodeData; item: Extract<NonNullable<CanvasNodeData["item"]>, { itemType: "retrieval-agent" }> }) {
  const cardRef = useRef<HTMLElement>(null);
  const hoverPreview = useRetrievalHoverPreview({ anchorRef: cardRef, buildId: node.buildId, item, onOpenDetail: () => node.onOpen(item, "business") });
  const run = item.run;
  const expanded = Boolean(node.expanded);
  const query = run.querySummary;
  const queryListId = `query-list-${run.eventId}`;
  return <><article ref={cardRef} className={`flowCard retrievalCard retrievalAgentCard status-${run.status}${expanded ? " isQueryExpanded" : ""}`} 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"><Bot size={14} />Agent 取数</span><span className={`agentRunStatus run-${run.status}`}>{run.status === "completed" ? "已完成" : run.status === "failed" ? "失败" : run.status === "interrupted" ? "构建中断" : "进行中"}</span></header>
    <h3>{run.businessLabel}</h3>
    <div className="agentTask"><b>取数目标</b><p>{run.taskPreview || "任务未记录"}</p></div>
    <div className="agentQuerySummary"><b>查询过程</b><p>{query.total} 次 · <span className="query-hit">{query.hit} 次命中</span> · <span className="query-empty">{query.empty} 次无结果</span>{query.failure ? <> · <span className="query-failure">{query.failure} 次失败</span></> : null}{query.interrupted ? <> · <span className="query-interrupted">{query.interrupted} 次中断</span></> : null}{query.unknown ? <> · <span className="query-unknown">{query.unknown} 次结果待确认</span></> : null}</p></div>
    <div className="agentScreening"><b>初筛整理</b><p>{run.screening.preview || (run.screening.state === "running" ? "正在整理查询结果" : "初筛整理未记录")}</p></div>
    {expanded ? <QueryAttemptList id={queryListId} attempts={run.attempts} roundIndex={item.roundIndex} branchId={item.branchId} onOpen={node.onOpen} /> : null}
    <footer>
      {run.attempts.length ? <button type="button" className="nodeAction nodrag nopan" aria-expanded={expanded} aria-controls={queryListId} onClick={(event) => { event.stopPropagation(); node.onToggleRetrievalAgent(item.id); }}>{expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}{expanded ? "收起查询" : `展开 ${run.attempts.length} 次查询`}</button> : null}
      <button type="button" className="nodeAction nodrag nopan" data-focus-return={`${item.id}:business`} onClick={(event) => { event.stopPropagation(); node.onOpen(item, "business"); }}>查看 Agent 详情<ArrowRight size={14} /></button>
      <SourceComparisonButton item={item} onOpen={node.onOpen} />
    </footer>
  </article>{hoverPreview.preview}</>;
}
