import { Fragment, useEffect, useMemo, useState } from 'react'
import {
  groupNodesByLayer,
  layerHint,
  layerLabel,
  nodeKindLabel,
  productFitTone,
  type KnowledgeGraphData,
  type KnowledgeGraphNode,
} from '../lib/knowledgeGraph'
import {
  buildSourceIndex,
  enrichSourceItem,
  type SourcePreviewItem,
} from '../lib/sourcePreview'
import { KnowledgeOrbitDiagram } from './KnowledgeOrbitDiagram'
import { KnowledgeLayerRipple } from './KnowledgeLayerRipple'
import { SourceLinkPreview } from './SourceLinkPreview'
import { Badge } from './ui'

type KnowledgeOverviewPanelProps = {
  graph: KnowledgeGraphData | null | undefined
  sources: SourcePreviewItem[]
}

function nodeSummary(node: KnowledgeGraphNode) {
  return node.placement_value?.trim() || node.relation?.trim() || '—'
}

function fitBadgeTone(score: number): 'brand' | 'sky' | 'neutral' {
  if (score >= 70) return 'brand'
  if (score >= 40) return 'sky'
  return 'neutral'
}

const TIER_RING_LABEL: Record<number, string> = {
  0: '核心',
  1: '延伸',
  2: '周邊',
}

function tierRingLabel(layer: number) {
  return TIER_RING_LABEL[layer] ?? layerLabel(layer)
}

function KnowledgeNodeTable({
  nodes,
  sourceIndex,
}: {
  nodes: KnowledgeGraphNode[]
  sourceIndex: Map<string, SourcePreviewItem>
}) {
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const sorted = useMemo(
    () => [...nodes].sort((a, b) => b.product_fit_score - a.product_fit_score),
    [nodes],
  )

  return (
    <div className="hx-knowledge-table-wrap">
      <table className="hx-knowledge-table">
        <thead>
          <tr>
            <th scope="col">節點</th>
            <th scope="col">類型</th>
            <th scope="col">相關度</th>
            <th scope="col">重點</th>
            <th scope="col">參考</th>
          </tr>
        </thead>
        <tbody>
          {sorted.map((node) => {
            const summary = nodeSummary(node)
            const evidence = (node.evidence ?? []).filter((item) => item.url?.trim())
            const expanded = expandedId === node.id
            const hasMore =
              (node.relation && node.relation !== summary) ||
              (node.placement_value && node.placement_value !== summary) ||
              evidence.length > 0

            return (
              <Fragment key={node.id}>
                <tr className={expanded ? 'hx-knowledge-table__row--open' : undefined}>
                  <td className="hx-knowledge-table__node">
                    <button
                      type="button"
                      className="hx-knowledge-table__node-btn"
                      onClick={() => hasMore && setExpandedId(expanded ? null : node.id)}
                      disabled={!hasMore}
                      aria-expanded={hasMore ? expanded : undefined}
                    >
                      <span
                        className={`hx-knowledge-table__fit hx-knowledge-table__fit--${productFitTone(node.product_fit_score)}`}
                        aria-hidden
                      />
                      <span className="hx-knowledge-table__label">{node.label}</span>
                      {hasMore ? (
                        <span className="hx-knowledge-table__toggle">{expanded ? '收合' : '展開'}</span>
                      ) : null}
                    </button>
                  </td>
                  <td>
                    <Badge tone="neutral">{nodeKindLabel(node.node_kind)}</Badge>
                  </td>
                  <td>
                    <Badge tone={fitBadgeTone(node.product_fit_score)}>{node.product_fit_score}</Badge>
                  </td>
                  <td className="hx-knowledge-table__summary">{summary}</td>
                  <td className="hx-knowledge-table__refs">
                    {evidence.length > 0 ? (
                      <div className="hx-knowledge-table__ref-chips">
                        {evidence.slice(0, 2).map((item, idx) => (
                          <SourceLinkPreview
                            key={`${item.url}-${idx}`}
                            item={enrichSourceItem(item, sourceIndex)}
                            compact
                          />
                        ))}
                      </div>
                    ) : (
                      <span className="hx-knowledge-table__empty">—</span>
                    )}
                  </td>
                </tr>
                {expanded && hasMore ? (
                  <tr className="hx-knowledge-table__detail-row">
                    <td colSpan={5}>
                      <div className="hx-knowledge-table__detail">
                        {node.relation ? (
                          <p>
                            <span className="hx-knowledge-table__detail-key">脈絡</span>
                            {node.relation}
                          </p>
                        ) : null}
                        {node.placement_value ? (
                          <p>
                            <span className="hx-knowledge-table__detail-key">為何相關</span>
                            {node.placement_value}
                          </p>
                        ) : null}
                        {evidence.length > 0 ? (
                          <div className="hx-knowledge-table__detail-refs">
                            {evidence.map((item, idx) => (
                              <SourceLinkPreview
                                key={`${item.url}-detail-${idx}`}
                                item={enrichSourceItem(item, sourceIndex)}
                                compact
                              />
                            ))}
                          </div>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                ) : null}
              </Fragment>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

export function KnowledgeOverviewPanel({ graph, sources }: KnowledgeOverviewPanelProps) {
  const grouped = useMemo(() => groupNodesByLayer(graph?.nodes ?? []), [graph?.nodes])
  const sourceIndex = useMemo(() => buildSourceIndex(sources), [sources])

  const [activeLayer, setActiveLayer] = useState<number>(() => grouped[0]?.[0] ?? 0)

  useEffect(() => {
    if (!grouped.some(([layer]) => layer === activeLayer)) {
      setActiveLayer(grouped[0]?.[0] ?? 0)
    }
  }, [grouped, activeLayer])

  const activeGroup = useMemo(
    () => grouped.find(([layer]) => layer === activeLayer) ?? grouped[0],
    [grouped, activeLayer],
  )

  const selectLayer = (layer: number) => {
    if (!grouped.some(([l]) => l === layer)) return
    const scrollY = window.scrollY
    setActiveLayer(layer)
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        window.scrollTo(0, scrollY)
      })
    })
  }

  if (!graph?.nodes?.length) {
    return (
      <p className="hx-research-reader__prose text-ink-secondary">延伸知識尚未產生。</p>
    )
  }

  const activeNodes = activeGroup?.[1] ?? []

  return (
    <div className="hx-knowledge-overview">
      <div className="hx-knowledge-overview__intro">
        <p className="hx-knowledge-overview__stats">
          <span>{graph.nodes.length} 個節點</span>
          {sources.length > 0 ? <span>· {sources.length} 個參考連結</span> : null}
          {graph.pain_tag_count > 0 ? <span>· {graph.pain_tag_count} 個痛點候選</span> : null}
        </p>
        <p className="hx-knowledge-overview__tip">
          點圓環或右側層級切換表格；圓心顯示目前層級。滑鼠移到連結可看摘要。
        </p>
      </div>

      <KnowledgeOrbitDiagram
        grouped={grouped}
        activeLayer={activeLayer}
        onSelectLayer={selectLayer}
      />

      <div className="hx-knowledge-tiers">
        {activeGroup ? (
          <section
            key={activeGroup[0]}
            className={`hx-knowledge-tier hx-knowledge-tier--active hx-knowledge-tier--l${Math.min(activeGroup[0], 2)}`}
            aria-labelledby={`knowledge-tier-${activeGroup[0]}`}
          >
            <header className="hx-knowledge-tier__head" id={`knowledge-tier-${activeGroup[0]}`}>
              <KnowledgeLayerRipple layer={activeGroup[0]} size="sm" />
              <div className="hx-knowledge-tier__head-text">
                <p className="hx-knowledge-tier__ring">{tierRingLabel(activeGroup[0])}</p>
                <p className="hx-knowledge-tier__title">{layerLabel(activeGroup[0])}</p>
                <p className="hx-knowledge-tier__hint">{layerHint(activeGroup[0])}</p>
              </div>
              <span className="hx-knowledge-tier__count">{activeNodes.length} 項</span>
            </header>
            <KnowledgeNodeTable nodes={activeNodes} sourceIndex={sourceIndex} />
          </section>
        ) : null}
      </div>

      {sources.length > 0 ? (
        <details className="hx-knowledge-sources">
          <summary className="hx-knowledge-sources__summary">
            參考連結
            <span className="hx-knowledge-sources__count">{sources.length}</span>
          </summary>
          <div className="hx-knowledge-sources__chips">
            {sources.map((item, index) => (
              <SourceLinkPreview
                key={`${item.url || item.title}-${index}`}
                item={item}
                compact
              />
            ))}
          </div>
        </details>
      ) : null}
    </div>
  )
}