import { useMemo } from 'react'
import {
  countSelectedNodes,
  groupNodesByLayer,
  layerLabel,
  nodeKindLabel,
  PAIN_TAG_MINIMUM,
  productFitTone,
  type KnowledgeGraphNode,
} from '../lib/knowledgeGraph'
import { Badge, Button, Notice } from './ui'

type KnowledgeGraphPanelProps = {
  nodes: KnowledgeGraphNode[]
  painTagCount: number
  seed: string
  loading?: boolean
  saving?: boolean
  onToggle: (nodeId: string, selected: boolean) => void
  onSelectPainNodes: () => void
  onClearSelection: () => void
  onSaveSelection: () => void
}

function TagList({ title, tags }: { title: string; tags: string[] }) {
  if (tags.length === 0) return null
  return (
    <div>
      <p className="text-[11px] font-bold text-muted">{title}</p>
      <div className="mt-1 flex flex-wrap gap-1.5">
        {tags.map((tag) => (
          <span
            key={tag}
            className="rounded-[var(--radius-pill)] border border-line bg-surface px-2 py-0.5 text-[11px] font-semibold text-ink-secondary"
          >
            {tag}
          </span>
        ))}
      </div>
    </div>
  )
}

export function KnowledgeGraphPanel({
  nodes,
  painTagCount,
  seed,
  loading,
  saving,
  onToggle,
  onSelectPainNodes,
  onClearSelection,
  onSaveSelection,
}: KnowledgeGraphPanelProps) {
  const selectedCount = useMemo(() => countSelectedNodes(nodes), [nodes])
  const grouped = useMemo(() => groupNodesByLayer(nodes), [nodes])
  const needsMorePain = painTagCount < PAIN_TAG_MINIMUM

  if (loading) {
    return <p className="text-sm text-ink-secondary">載入知識圖譜…</p>
  }

  if (nodes.length === 0) {
    return (
      <Notice
        tone="info"
        title="尚未建立知識圖譜"
        message="輸入種子詞（例如「敏感肌」）並按「Brave 擴展圖譜」。完成後可在此勾選要海巡的節點與 tag。"
      />
    )
  }

  return (
    <div className="grid gap-5">
      <div className="flex flex-wrap items-center gap-2">
        <Badge tone="brand">種子：{seed}</Badge>
        <Badge tone={needsMorePain ? 'warning' : 'success'}>
          痛點候選 {painTagCount} / {PAIN_TAG_MINIMUM}
        </Badge>
        <Badge tone="sky">已勾選 {selectedCount} 節點</Badge>
      </div>

      {needsMorePain ? (
        <Notice
          tone="warning"
          title="痛點 tag 仍不足"
          message={`目前 ${painTagCount} 個痛點候選，建議至少 ${PAIN_TAG_MINIMUM} 個。可執行「補充擴展」或換更精準的種子詞重跑。`}
        />
      ) : null}

      <div className="flex flex-wrap gap-2">
        <Button variant="soft" onClick={onSelectPainNodes} data-islander-label="勾選痛點節點">
          勾選痛點節點
        </Button>
        <Button variant="ghost" onClick={onClearSelection}>
          清除勾選
        </Button>
        <Button onClick={onSaveSelection} disabled={saving} data-islander-label="儲存勾選">
          {saving ? '儲存中…' : '儲存勾選'}
        </Button>
      </div>

      <div className="grid gap-4">
        {grouped.map(([layer, layerNodes]) => (
          <section key={layer}>
            <p className="mb-2 text-xs font-black tracking-wide text-brand uppercase">
              {layerLabel(layer)} · {layerNodes.length} 節點
            </p>
            <div className="grid gap-3">
              {layerNodes.map((node) => {
                const fitTone = productFitTone(node.product_fit_score)
                return (
                  <label
                    key={node.id}
                    className={`ac-island-card flex cursor-pointer gap-3 p-4 transition ${
                      node.selected_for_scan ? 'ring-2 ring-brand/50' : ''
                    }`}
                    data-islander-label={`圖譜節點 ${node.label}`}
                  >
                    <input
                      type="checkbox"
                      className="mt-1 h-4 w-4 shrink-0 accent-[var(--hx-brand)]"
                      checked={node.selected_for_scan}
                      onChange={(e) => onToggle(node.id, e.target.checked)}
                    />
                    <div className="min-w-0 flex-1 space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="font-bold text-ink">{node.label}</span>
                        <Badge tone="neutral">{nodeKindLabel(node.node_kind)}</Badge>
                        {node.placement_value ? (
                          <Badge tone="sky">{node.placement_value}</Badge>
                        ) : null}
                        <Badge
                          tone={
                            fitTone === 'success'
                              ? 'success'
                              : fitTone === 'warning'
                                ? 'warning'
                                : 'neutral'
                          }
                        >
                          產品匹配 {node.product_fit_score}
                        </Badge>
                      </div>
                      {node.relation ? (
                        <p className="text-xs text-muted">關係：{node.relation}</p>
                      ) : null}
                      <div className="grid gap-2 sm:grid-cols-2">
                        <TagList title="相關軌 tag" tags={node.relevance_tags} />
                        <TagList title="近期軌 tag" tags={node.recency_tags} />
                      </div>
                    </div>
                  </label>
                )
              })}
            </div>
          </section>
        ))}
      </div>
    </div>
  )
}