import { useMemo, useState } from 'react'
import { generateTopicTableQueries, getTopicTableQueryPrompt } from '../../api/workbench.js'

const EXAMPLE = {
  topicBuildId: '1229',
  topicId: '1392',
}

const ROUTES = [
  { key: 'unique_hook', inputTitle: '灵感点和特殊组合' },
  { key: 'goal_execution', inputTitle: '目标和想达到的效果' },
  { key: 'key_execution', inputTitle: '关键镜头和动作要求' },
  { key: 'cross_dimension', inputTitle: '实质、形式、意图三类元素' },
  { key: 'account_fit', inputTitle: '账号原来的内容风格' },
  { key: 'evidence_gap', inputTitle: '参考案例和元素来源' },
]

function shortText(value, max = 120) {
  const text = String(value || '').trim()
  return text.length > max ? `${text.slice(0, max)}…` : text
}

function firstItems(values, max = 4) {
  return [...new Set((values || []).filter(Boolean).map((value) => shortText(value)))].slice(0, max)
}

function joinNames(values, max = 8) {
  const names = values || []
  if (names.length <= max) return names.join('、')
  return `${names.slice(0, max).join('、')}等`
}

function sourceItems(result, route) {
  const topic = result.topic || {}
  const groups = topic.input_groups || {}
  const points = groups.points || {}
  const dimensions = topic.dimensions || {}
  const direction = topic.topic_direction || {}
  const preferences = direction.persona_dimensions || {}

  if (route === 'unique_hook') {
    return firstItems(points['灵感点'] || [topic.result])
  }
  if (route === 'goal_execution') {
    return firstItems([
      ...(points['目的点'] || []),
      dimensions['意图']?.length ? `想达到的效果：${joinNames(dimensions['意图'])}` : '',
    ])
  }
  if (route === 'key_execution') {
    return firstItems([
      ...(points['关键点'] || []),
      dimensions['形式']?.length ? `拍摄形式：${joinNames(dimensions['形式'])}` : '',
    ])
  }
  if (route === 'cross_dimension') {
    return firstItems([
      dimensions['实质']?.length ? `内容里有什么：${joinNames(dimensions['实质'])}` : '',
      dimensions['形式']?.length ? `怎么呈现：${joinNames(dimensions['形式'])}` : '',
      dimensions['意图']?.length ? `想达到什么效果：${joinNames(dimensions['意图'])}` : '',
    ])
  }
  if (route === 'account_fit') {
    return firstItems([
      preferences['实质偏好'] ? `常拍内容：${preferences['实质偏好']}` : '',
      preferences['形式偏好'] ? `常用拍法：${preferences['形式偏好']}` : '',
      preferences['意图偏好'] ? `希望观众感受到：${preferences['意图偏好']}` : '',
    ], 3)
  }
  return firstItems((groups.reference_notes || []).map((row) => `${row.element}：${row.note}`), 3)
}

function PromptModal({ payload, loading, error, onClose }) {
  return (
    <div className="manual-modal-mask" onClick={onClose}>
      <section className="manual-modal-panel topic-prompt-modal" onClick={(event) => event.stopPropagation()}>
        <header className="manual-modal-head">
          <div>
            <span className="topic-eyebrow">选题表信息 → 大模型判断 → 搜索词</span>
            <h2>生成 Prompt</h2>
            <p>{payload ? `${payload.name} · ${payload.version}` : '读取当前线上使用的完整 Prompt'}</p>
          </div>
          <button className="manual-close" type="button" onClick={onClose} aria-label="关闭">×</button>
        </header>
        {loading && <div className="topic-inline-state">正在读取 Prompt…</div>}
        {error && <div className="manual-error">{error}</div>}
        {payload && (
          <>
            <div className="topic-route-strip">
              {(payload.routes || []).map((route) => (
                <span key={route.key}>{route.label}</span>
              ))}
            </div>
            <pre className="topic-prompt-code">{payload.system_prompt}</pre>
          </>
        )}
      </section>
    </div>
  )
}

function GenerationRows({ result }) {
  const rows = useMemo(() => ROUTES.map((route, index) => ({
    ...route,
    number: index + 1,
    need: (result.knowledge_needs || []).find((need) => need.route === route.key),
    queries: (result.queries || []).filter((query) => query.route === route.key),
    inputs: sourceItems(result, route.key),
  })), [result])

  return (
    <section className="topic-route-map">
      <div className="topic-route-map-head">
        <strong>选题表里用到的信息</strong>
        <strong>大模型判断什么</strong>
        <strong>生成哪些具体搜索词</strong>
      </div>
      <div className="topic-route-map-body">
        {rows.map((row) => (
          <article className={`topic-route-row route-${row.key}`} key={row.key}>
            <div className="topic-route-input">
              <span>第 {row.number} 种</span>
              <h3>{row.inputTitle}</h3>
              <ul>
                {row.inputs.map((item) => <li key={item}>{item}</li>)}
              </ul>
            </div>
            <div className="topic-route-judgement">
              <p>{row.need?.decision_context || '这类信息没有形成需要判断的问题'}</p>
            </div>
            <div className="topic-route-queries">
              {row.queries.map((query, index) => (
                <div key={`${query.query}-${index}`}>
                  <b>{index + 1}</b>
                  <p>{query.query}</p>
                </div>
              ))}
            </div>
          </article>
        ))}
      </div>
    </section>
  )
}

export default function TopicTableQueryPanel() {
  const [topicBuildId, setTopicBuildId] = useState(EXAMPLE.topicBuildId)
  const [topicId, setTopicId] = useState(EXAMPLE.topicId)
  const [result, setResult] = useState(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [promptOpen, setPromptOpen] = useState(false)
  const [prompt, setPrompt] = useState(null)
  const [promptLoading, setPromptLoading] = useState(false)
  const [promptError, setPromptError] = useState('')

  const showPrompt = async () => {
    setPromptOpen(true)
    if (prompt || promptLoading) return
    setPromptLoading(true)
    setPromptError('')
    try {
      setPrompt(await getTopicTableQueryPrompt())
    } catch (e) {
      setPromptError(e.message || 'Prompt 读取失败')
    } finally {
      setPromptLoading(false)
    }
  }

  const generate = async (event) => {
    event.preventDefault()
    setLoading(true)
    setError('')
    try {
      const payload = {
        topic_build_id: Number(topicBuildId),
        topic_id: topicId ? Number(topicId) : null,
        max_queries: 18,
      }
      setResult(await generateTopicTableQueries(payload))
    } catch (e) {
      setError(e.message || '搜索词生成失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="topic-table-panel">
      <header className="topic-table-intro">
        <div>
          <span className="topic-eyebrow">第四种生成方式</span>
          <h2>根据选题表生成搜索词</h2>
          <p>每一类选题信息，都对应一项大模型判断和一组具体搜索词。</p>
        </div>
        <span className="topic-preview-only">这里只生成搜索词，不会开始搜索</span>
      </header>

      <form className="topic-table-form" onSubmit={generate}>
        <label>
          <span>选题表编号</span>
          <input value={topicBuildId} onChange={(e) => setTopicBuildId(e.target.value)} type="number" min="1" required />
        </label>
        <label>
          <span>选题编号</span>
          <input value={topicId} onChange={(e) => setTopicId(e.target.value)} type="number" min="1" placeholder="不填则取 mature 选题" />
        </label>
        <button className="topic-example-button" type="button" onClick={() => {
          setTopicBuildId(EXAMPLE.topicBuildId)
          setTopicId(EXAMPLE.topicId)
          setResult(null)
          setError('')
        }}>载入真实示例 1229</button>
        <button className="topic-prompt-button" type="button" onClick={showPrompt}>查看生成 Prompt</button>
        <button className="topic-generate-button" type="submit" disabled={loading}>
          {loading ? '大模型正在生成…' : '生成搜索词'}
        </button>
      </form>

      {error && <div className="manual-error topic-generation-error">{error}</div>}
      {!result && !loading && (
        <section className="topic-example-map">
          <div className="topic-example-cell">
            <span>第 1 种 · 灵感点和特殊组合</span>
            <p>樱花树下低角度拍小羊，用 CCD 记录彩虹光晕</p>
          </div>
          <div className="topic-example-cell">
            <span>大模型判断什么</span>
            <p>这个画面里的彩虹光晕，怎样才能稳定拍出来？</p>
          </div>
          <div className="topic-example-cell">
            <span>生成的搜索词</span>
            <ul>
              <li>逆光人像怎么拍出自然彩虹光晕</li>
              <li>低角度拍摄时太阳和镜头怎么配合</li>
            </ul>
          </div>
        </section>
      )}
      {loading && <div className="topic-loading-card"><span />正在读取选题表，并逐类生成搜索词…</div>}
      {result && <GenerationRows result={result} />}
      {promptOpen && (
        <PromptModal
          payload={prompt}
          loading={promptLoading}
          error={promptError}
          onClose={() => setPromptOpen(false)}
        />
      )}
    </div>
  )
}
