import React, { useEffect, useMemo, useState } from 'react'

const AXIS_LABEL = {
  实质: '实质（3-4层）',
  形式: '形式（3-4层）',
}

const PLATFORM_LABEL = {
  xiaohongshu: ['小红书', 'xhs'],
  weixin: ['微信公众号', 'wx'],
  douyin: ['抖音', 'dy'],
}

function params() {
  return new URLSearchParams(window.location.search)
}

function statusText(status) {
  return {
    pending: '等待中',
    running: '运行中',
    done: '完成',
    partial: '部分完成',
    failed: '失败',
    skipped: '跳过',
  }[status] || status || '未开始'
}

function querySummaryMap(summary) {
  const out = new Map()
  for (const row of summary?.queries || []) {
    out.set(row.query_id, row)
  }
  return out
}

function platformCounts(row) {
  const platforms = row?.platforms || {}
  return ['xiaohongshu', 'weixin', 'douyin'].map((key) => platforms[key]?.status || '未跑').join(' / ')
}

function decodedLabel(row) {
  if (!row) return ''
  return `${row.decoded_count || 0}/${row.candidate_count || 0} 已拆`
}

function knowledgeLabel(row) {
  if (!row) return ''
  const hits = Math.max(row.creation_hit_count || 0, row.decoded_count || 0)
  return `${hits}/${row.candidate_count || 0} 知识贴`
}

function uniqueAxisValues(items, axis) {
  const seen = new Set()
  const out = []
  for (const item of items || []) {
    const value = item.parts?.[axis]
    if (value && !seen.has(value)) {
      seen.add(value)
      out.push(value)
    }
  }
  return out
}

function axisValues(data, family, axis) {
  if (axis === '实质' || axis === '形式') {
    return uniqueAxisValues(family.items, axis)
  }
  const key = axis === '作用/感受/意图' ? '目的池' : axis
  return data.axis_values?.[key] || uniqueAxisValues(family.items, key)
}

function AxisColumn({ data, family, axis }) {
  const values = axisValues(data, family, axis)
  return (
    <div className="axcol">
      <div className="axhd">
        <span>{AXIS_LABEL[axis] || axis}</span>
        <span className="gn">{values.length}</span>
      </div>
      <div className="axlist">
        {values.map((value) => <div className="axv" key={value}>{value}</div>)}
      </div>
    </div>
  )
}

function singletonMaps(singleton) {
  const byQueryText = new Map()
  const decodedByQueryId = new Map()
  for (const item of singleton?.decoded_items || []) {
    const key = item.query_id || ''
    decodedByQueryId.set(key, [...(decodedByQueryId.get(key) || []), item])
  }
  for (const row of singleton?.queries || []) {
    byQueryText.set(row.query_text, {
      ...row,
      decoded_items: decodedByQueryId.get(row.query_id) || [],
    })
  }
  return byQueryText
}

function PreviewQueryRow({ item, index, latest }) {
  return (
    <div className={`qrow ${item.keep === false ? 'drop' : 'keep'}`} key={`${item.query}-${index}`} title={item.reason || ''}>
      <span className="qmark">{item.keep === false ? '✕' : '✓'}</span>
      {typeof item.valid === 'number' && (
        <span className={`qvalid ${item.valid >= 6 ? 'ok' : 'low'}`}>语义{item.valid}</span>
      )}
      <span className="qtext">{item.query}</span>
      {latest ? (
        <>
          <span className="qcreation done">{decodedLabel(latest)}</span>
          <span className="qcreation knowledge">{knowledgeLabel(latest)}</span>
          <a className="qdetail on" href={`#/query/latest/${encodeURIComponent(latest.query_id)}`}>查看详情</a>
        </>
      ) : (
        <span className="qdetail">未搜索</span>
      )}
      {item.reason && <span className="qreason">{item.reason}</span>}
    </div>
  )
}

function QueryGenerationPreview() {
  const [data, setData] = useState(null)
  const [singleton, setSingleton] = useState(null)
  const [activeKey, setActiveKey] = useState('f1')
  const [err, setErr] = useState('')

  useEffect(() => {
    setErr('')
    Promise.all([
      fetch('/api/query-generation/preview?per=0&batch_n=0&dry=true')
        .then((r) => (r.ok ? r.json() : Promise.reject(new Error('query 生成预览读取失败')))),
      fetch('/api/query-generation/latest-singleton')
        .then((r) => (r.ok ? r.json() : null))
        .catch(() => null),
    ])
      .then(([payload, latest]) => {
        setData(payload)
        setSingleton(latest)
        const firstKey = payload.families?.[0]?.key
        if (firstKey) setActiveKey(firstKey)
      })
      .catch((e) => setErr(e.message || '读取失败'))
  }, [])

  if (err) return <div className="empty">{err}</div>
  if (!data) return <div className="empty">加载中...</div>

  const families = data.families || []
  const family = families.find((row) => row.key === activeKey) || families[0]
  const kept = (family?.items || []).filter((item) => item.keep !== false).length
  const latestByQuery = singletonMaps(singleton)

  return (
    <div>
      <h1>创作知识 · Query 正交 Demo</h1>
      <div className="sub">
        只显示当前激活的 2 种正交方式：f1 / f2。生成逻辑来自正式 query builder；此页只预览，不写 DB、不发起搜索。
      </div>

      <div className="famcols two">
        {families.map((row) => (
          <button
            className={`fbtn ${row.key === family.key ? 'on' : ''}`}
            key={row.key}
            type="button"
            onClick={() => setActiveKey(row.key)}
          >
            <span className="fbtn-pre">{row.axes?.[0] || row.key}</span>
            <span className="fbtn-suf">{(row.axes || []).slice(1).join(' × ')}</span>
          </button>
        ))}
      </div>

      <div className="cdemo">
        {(family.axes || []).map((axis) => <AxisColumn key={axis} axis={axis} data={data} family={family} />)}
        <div className="axcol qcol">
          <div className="axhd qhd">
            <span>Query 词</span>
            <span className="qhd-metrics">
              <span className="avgcreation pending">预览</span>
              <span className="gn">留 {kept}/{family.items?.length || 0}</span>
            </span>
          </div>
          <div className="axlist">
            {(family.items || []).map((item, index) => {
              const latest = latestByQuery.get(item.query)
              return (
                <PreviewQueryRow
                  item={item}
                  index={index}
                  key={`${item.query}-${index}`}
                  latest={latest}
                />
              )
            })}
          </div>
        </div>
      </div>
    </div>
  )
}

export default function CreationDemo() {
  const [batch, setBatch] = useState(null)
  const [summary, setSummary] = useState(null)
  const [err, setErr] = useState('')
  const search = params()
  const batchId = search.get('batch_id') || ''
  const runId = search.get('run_id') || ''
  const summaryByQuery = useMemo(() => querySummaryMap(summary), [summary])

  useEffect(() => {
    setErr('')
    setBatch(null)
    setSummary(null)
    if (!batchId) {
      return
    }
    fetch(`/api/query-batches/${encodeURIComponent(batchId)}`)
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('query batch 读取失败'))))
      .then(setBatch)
      .catch((e) => setErr(e.message || '读取失败'))
    if (runId) {
      fetch(`/api/acquisition/runs/${encodeURIComponent(runId)}/summary`)
        .then((r) => (r.ok ? r.json() : Promise.reject(new Error('run summary 读取失败'))))
        .then(setSummary)
        .catch(() => setSummary(null))
    }
  }, [batchId, runId])

  if (!batchId) {
    return <QueryGenerationPreview />
  }
  if (err) return <div className="empty">{err}</div>
  if (!batch) return <div className="empty">加载中...</div>

  const queries = batch.queries || []
  return (
    <div>
      <h1>创作知识采集工作台</h1>
      <div className="sub">
        {batch.batch?.name || 'Query Batch'} · {queries.length} 条 query
        {summary && <span> · 候选 {summary.candidate_count} · 命中 {summary.creation_hit_count}</span>}
      </div>

      <div className="cdemo single">
        <div className="axcol qcol wide">
          <div className="axhd qhd">
            <span>Query</span>
            <span className="qhd-metrics">
              {runId && <span className="avgcreation">{statusText(summary?.status)}</span>}
              <span className="gn">{queries.length}</span>
            </span>
          </div>
          <div className="axlist">
            {queries.map((query) => {
              const qsum = summaryByQuery.get(query.id)
              const href = runId ? `#/query/${encodeURIComponent(runId)}/${encodeURIComponent(query.id)}` : '#/'
              return (
                <div className={`qrow ${query.keep === false ? 'drop' : 'keep'}`} key={query.id} title={query.filter_reason || ''}>
                  <span className="qmark">{query.keep === false ? '✕' : '✓'}</span>
                  <span className="qtext">{query.query_text}</span>
                  {qsum && (
                    <span className="qcreation done">
                      {qsum.creation_hit_count}/{qsum.candidate_count} 命中
                    </span>
                  )}
                  {runId ? (
                    <a className="qdetail on" href={href}>查看素材<span>{platformCounts(qsum)}</span></a>
                  ) : (
                    <span className="qdetail">待运行</span>
                  )}
                  {query.filter_reason && <span className="qreason">{query.filter_reason}</span>}
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </div>
  )
}
