import { useEffect, useMemo, useState, type CSSProperties } from 'react'
import { KnowledgeLayerRipple } from './KnowledgeLayerRipple'
import { layerHint, layerLabel, type KnowledgeGraphNode } from '../lib/knowledgeGraph'

type LayerGroup = [number, KnowledgeGraphNode[]]

type KnowledgeOrbitDiagramProps = {
  grouped: LayerGroup[]
  activeLayer: number
  onSelectLayer: (layer: number) => void
}

const TIER_META: Record<number, { ring: string; title: string }> = {
  0: { ring: '核心', title: '最內圈' },
  1: { ring: '延伸', title: '中圈' },
  2: { ring: '周邊', title: '外圈' },
}

function tierMeta(layer: number) {
  return TIER_META[layer] ?? { ring: layerLabel(layer), title: `L${layer}` }
}

function topLabels(nodes: KnowledgeGraphNode[], limit = 2) {
  return [...nodes]
    .sort((a, b) => b.product_fit_score - a.product_fit_score)
    .slice(0, limit)
    .map((node) => node.label)
}

const RING_LAYERS = [
  { layer: 2, className: 'l2', label: '周邊層' },
  { layer: 1, className: 'l1', label: '延伸層' },
  { layer: 0, className: 'l0', label: '核心層' },
] as const

export function KnowledgeOrbitDiagram({
  grouped,
  activeLayer,
  onSelectLayer,
}: KnowledgeOrbitDiagramProps) {
  const [pulseLayer, setPulseLayer] = useState<number | null>(null)
  const [pulseTick, setPulseTick] = useState(0)

  const tiers = useMemo(
    () =>
      grouped.map(([layer, nodes]) => ({
        layer,
        nodes,
        labels: topLabels(nodes),
        meta: tierMeta(layer),
      })),
    [grouped],
  )

  const rowCount = Math.max(tiers.length, 1)
  const layerSet = useMemo(() => new Set(grouped.map(([layer]) => layer)), [grouped])
  const activeMeta = tierMeta(activeLayer)

  useEffect(() => {
    if (pulseLayer === null) return
    const timer = window.setTimeout(() => setPulseLayer(null), 520)
    return () => window.clearTimeout(timer)
  }, [pulseLayer])

  const selectLayer = (layer: number) => {
    if (!layerSet.has(layer)) return
    setPulseLayer(layer)
    setPulseTick((tick) => tick + 1)
    onSelectLayer(layer)
  }

  return (
    <div className="hx-knowledge-orbit-map" aria-label="知識圖譜由核心向外擴展">
      <div
        className="hx-knowledge-orbit-map__rings-col"
        style={{ '--hx-orbit-rows': rowCount } as CSSProperties}
      >
        <div className="hx-knowledge-orbit-map__rings" role="group" aria-label="點選圓環切換層級">
          {RING_LAYERS.map(({ layer, className }) =>
            layerSet.has(layer) ? (
              <span
                key={`ring-${layer}`}
                className={`hx-knowledge-orbit-map__ring hx-knowledge-orbit-map__ring--${className} ${activeLayer === layer ? 'hx-knowledge-orbit-map__ring--active' : ''} ${pulseLayer === layer ? 'hx-knowledge-orbit-map__ring--pulse' : ''}`}
                aria-hidden
              />
            ) : null,
          )}

          {pulseLayer !== null && layerSet.has(pulseLayer) ? (
            <span
              key={`ripple-${pulseLayer}-${pulseTick}`}
              className={`hx-knowledge-orbit-map__ripple hx-knowledge-orbit-map__ripple--l${pulseLayer}`}
              aria-hidden
            />
          ) : null}

          {RING_LAYERS.map(({ layer, className, label }) =>
            layerSet.has(layer) ? (
              <button
                key={`hit-${layer}`}
                type="button"
                className={`hx-knowledge-orbit-map__ring-hit hx-knowledge-orbit-map__ring-hit--${className} ${activeLayer === layer ? 'hx-knowledge-orbit-map__ring-hit--active' : ''}`}
                aria-label={`${label}，${tierMeta(layer).ring}`}
                aria-pressed={activeLayer === layer}
                title={`查看${tierMeta(layer).ring}`}
                onMouseDown={(event) => event.preventDefault()}
                onClick={() => selectLayer(layer)}
              />
            ) : null,
          )}

          {RING_LAYERS.map(({ layer, className }) =>
            layerSet.has(layer) ? (
              <span
                key={`tag-${layer}`}
                className={`hx-knowledge-orbit-map__ring-tag hx-knowledge-orbit-map__ring-tag--${className} ${activeLayer === layer ? 'hx-knowledge-orbit-map__ring-tag--active' : ''} ${pulseLayer === layer ? 'hx-knowledge-orbit-map__ring-tag--pulse' : ''}`}
                aria-hidden
              >
                {tierMeta(layer).ring}
              </span>
            ) : null,
          )}

          <div
            className={`hx-knowledge-orbit-map__core ${pulseLayer !== null ? 'hx-knowledge-orbit-map__core--pulse' : ''}`}
            aria-live="polite"
          >
            <KnowledgeLayerRipple layer={activeLayer} size="sm" />
            <span className="hx-knowledge-orbit-map__core-now">正在看</span>
            <span key={activeLayer} className="hx-knowledge-orbit-map__core-tier">
              {activeMeta.ring}
            </span>
          </div>
        </div>
        <p className="hx-knowledge-orbit-map__rings-hint">點圓環切換層級</p>
      </div>

      <div
        className="hx-knowledge-orbit-map__tiers-col"
        style={{ '--hx-orbit-rows': rowCount } as CSSProperties}
        role="tablist"
        aria-label="知識圖譜層級"
      >
        {tiers.map(({ layer, nodes, labels, meta }) => {
          const active = activeLayer === layer
          return (
            <button
              key={layer}
              type="button"
              role="tab"
              aria-selected={active}
              className={`hx-knowledge-orbit-map__tier ${active ? 'hx-knowledge-orbit-map__tier--active' : ''} hx-knowledge-orbit-map__tier--l${Math.min(layer, 2)}`}
              onMouseDown={(event) => event.preventDefault()}
              onClick={() => selectLayer(layer)}
            >
              <KnowledgeLayerRipple layer={layer} size="sm" />
              <span className="hx-knowledge-orbit-map__tier-main">
                <span className="hx-knowledge-orbit-map__tier-head">
                  <span className="hx-knowledge-orbit-map__tier-ring">{meta.ring}</span>
                  <span className="hx-knowledge-orbit-map__tier-sub">
                    {meta.title} · {layerLabel(layer)} · {nodes.length} 項
                  </span>
                </span>
                <span className="hx-knowledge-orbit-map__tier-hint">{layerHint(layer)}</span>
                {labels.length > 0 ? (
                  <span className="hx-knowledge-orbit-map__tier-samples">
                    {labels.join(' · ')}
                    {nodes.length > labels.length ? ` · +${nodes.length - labels.length}` : ''}
                  </span>
                ) : null}
              </span>
            </button>
          )
        })}
      </div>
    </div>
  )
}