import { useEffect, useMemo, useState } from 'react'
import { getDecodeItemDetail } from '../../api/decode.js'
import ErrorState from '../../components/ErrorState.jsx'
import LoadingState from '../../components/LoadingState.jsx'
import {
  KnowledgeCard,
  PayloadModal,
  Ribbon,
  SourceDetails,
} from './components.jsx'

export default function DecodeKnowledgeModal({ itemId, embedded = true, onClose }) {
  const [data, setData] = useState(null)
  const [err, setErr] = useState('')
  const [jsonPayload, setJsonPayload] = useState(null)
  const [zoom, setZoom] = useState(null)

  useEffect(() => {
    setData(null)
    setErr('')
    if (!itemId) {
      setErr('缺少 item_id')
      return undefined
    }
    const controller = new AbortController()
    getDecodeItemDetail(itemId, { signal: controller.signal })
      .then(setData)
      .catch((e) => {
        if (e.name !== 'AbortError') setErr(e.message || '读取失败')
      })
    return () => controller.abort()
  }, [itemId])

  const scopesByParticle = useMemo(() => {
    const map = new Map()
    for (const scope of data?.scope_results || []) {
      const key = scope.particle_id || ''
      map.set(key, [...(map.get(key) || []), scope])
    }
    return map
  }, [data])

  const payloadByParticle = useMemo(() => {
    const map = new Map()
    for (const draft of data?.payload_drafts || []) {
      if (draft.particle_id) map.set(draft.particle_id, draft)
    }
    return map
  }, [data])

  const pageClass = `legacy-decode-page${embedded ? ' embedded-decode-page' : ''}`

  if (err) return <div className={pageClass}><ErrorState>{err}</ErrorState></div>
  if (!data) return <div className={pageClass}><LoadingState /></div>

  const particles = data.knowledge_particles || []
  const readText = data.decode_result?.read_result?.text || ''

  return (
    <div className={pageClass}>
      <div className="app">
        <header className="top">
          <h1>创作知识的解构</h1>
          <div className="picker">
            {embedded ? (
              <button className="pill" type="button" onClick={onClose}>关闭弹窗</button>
            ) : (
              <a className="pill" href="#/">返回 Query 看板</a>
            )}
            <span className="pill on">{data.item?.title || '真实单例'}<span className="n">{particles.length}颗</span></span>
          </div>
        </header>
        <div className="scroll">
          <Ribbon />
          <SourceDetails item={data.item} readText={readText} onZoom={setZoom} />
          <div className="barhint">
            这一帖拆出 <b>{particles.length}</b> 颗知识（how 工序表 / what 知识卡 / why 论点卡）；每颗知识右上角可打开 payload。
          </div>
          {particles.map((particle, idx) => (
            <KnowledgeCard
              key={particle.id}
              particle={particle}
              idx={idx}
              scopes={scopesByParticle.get(particle.id) || []}
              payload={payloadByParticle.get(particle.id)}
              onJson={setJsonPayload}
            />
          ))}
        </div>
      </div>
      <PayloadModal payload={jsonPayload} onClose={() => setJsonPayload(null)} />
      {zoom && <div className="lb" onClick={() => setZoom(null)}><img src={zoom} alt="" /></div>}
    </div>
  )
}
