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,
  SourceDetails,
} from '../decode/components.jsx'

function statusText(data) {
  const item = data?.item || {}
  const result = data?.decode_result
  const particles = data?.knowledge_particles || []
  if (particles.length > 0) return `已提取 ${particles.length} 颗知识`
  if (result?.status === 'decoded') return '已解构，无知识'
  if (result?.status) return `解构状态：${result.status}`
  if (item.classification?.is_creation_knowledge === false) return '粗筛非创作知识'
  return '无知识'
}

export default function ItemDetailPage({ itemId }) {
  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])

  if (err) return <ErrorState>{err}</ErrorState>
  if (!data) return <LoadingState />

  const particles = data.knowledge_particles || []
  const readText = data.decode_result?.read_result?.text || ''
  const originalText = data.item?.body_text || ''
  const summaryText = data.item?.raw_summary || ''

  return (
    <div className="item-detail-page">
      <div className="item-detail-top">
        <a className="back" href="#/">返回 Query 看板</a>
        <span className="item-detail-state">{statusText(data)}</span>
      </div>
      <div className="item-detail-layout">
        <section className="item-post-pane">
          <div className="pane-head">
            <span>原帖</span>
            <b>{data.item?.platform || 'unknown'}</b>
          </div>
          <SourceDetails item={data.item} readText="" originalText={originalText} onZoom={setZoom} />
          {!originalText && (
            <div className="item-body-copy item-missing-original">
              未取到平台原文全文
            </div>
          )}
          {summaryText && summaryText !== originalText && (
            <details className="item-body-copy" open>
              <summary>正文摘要</summary>
              <div>{summaryText}</div>
            </details>
          )}
          {readText && (
            <details className="item-body-copy item-read-result">
              <summary>读懂后的内容</summary>
              <div>{readText}</div>
            </details>
          )}
        </section>

        <section className="item-knowledge-pane legacy-decode-page embedded-decode-page">
          <div className="pane-head">
            <span>提取知识</span>
            <b>{particles.length} 颗</b>
          </div>
          {particles.length === 0 ? (
            <div className="no-knowledge">无知识</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}
              />
            ))
          )}
        </section>
      </div>
      <div className="legacy-decode-page embedded-decode-page item-payload-modal-scope">
        <PayloadModal payload={jsonPayload} onClose={() => setJsonPayload(null)} />
      </div>
      {zoom && (
        <div className="item-lightbox" onClick={() => setZoom(null)}>
          <img src={zoom} alt="" />
        </div>
      )}
    </div>
  )
}
