import { useMemo } from 'react'
import type { KnowledgeGraphData, KnowledgeGraphNode } from '../lib/knowledgeGraph'
import { mergeCopyMissionSources } from '../lib/copyMissionGraph'
import type { CopyMissionData } from '../types/copyMission'
import { KnowledgeOverviewPanel } from './KnowledgeOverviewPanel'
import { Button, Notice } from './ui'

type Props = {
  mission: CopyMissionData
  graph: KnowledgeGraphData | null
  graphLoading?: boolean
  draftNodes: KnowledgeGraphNode[]
  saving?: boolean
  expanding?: boolean
  discoverReady?: boolean
  onToggle: (nodeId: string, selected: boolean) => void
  onSelectPainNodes: () => void
  onClearSelection: () => void
  onSaveSelection: () => void
  onExpandKnowledge: () => void
}

export function CopyMissionKnowledgeTab({
  mission,
  graph,
  graphLoading,
  draftNodes,
  saving,
  expanding,
  discoverReady,
  onToggle,
  onSelectPainNodes,
  onClearSelection,
  onSaveSelection,
  onExpandKnowledge,
}: Props) {
  const sources = useMemo(
    () => mergeCopyMissionSources(mission.research_map, graph),
    [mission.research_map, graph],
  )
  const hasGraph = (graph?.nodes?.length ?? 0) > 0

  if (graphLoading && !hasGraph) {
    return <p className="text-sm leading-relaxed text-ink-secondary">載入延伸知識…</p>
  }

  if (!hasGraph) {
    return (
      <div className="space-y-4">
        <Notice
          tone="info"
          title="延伸知識圖譜尚未建立"
          message="先完成研究地圖，再按「擴展延伸知識」從網搜與 AI 展開核心／延伸／周邊節點，勾選後即可餵給矩陣產文。"
        />
        {discoverReady === false ? (
          <Notice
            tone="warning"
            title="建議設定 Brave 或 Exa"
            message="有網搜管道時圖譜會更完整；僅 AI key 也能以 LLM 模式產生基礎節點。"
          />
        ) : null}
        <Button variant="soft" onClick={onExpandKnowledge} disabled={expanding}>
          {expanding ? '擴展中…' : '擴展延伸知識'}
        </Button>
      </div>
    )
  }

  return (
    <KnowledgeOverviewPanel
      graph={graph}
      sources={sources}
      nodes={draftNodes}
      selectable
      saving={saving}
      expanding={expanding}
      onToggle={onToggle}
      onSelectPainNodes={onSelectPainNodes}
      onClearSelection={onClearSelection}
      onSaveSelection={onSaveSelection}
      onExpandKnowledge={onExpandKnowledge}
    />
  )
}