import { useCallback, useEffect, useState } from 'react'
import { generateTopicTableQueries, getTopicTableQueryPrompt, getTopicTableSources } from '../../api/workbench.js'

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

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 && <pre className="topic-prompt-code">{payload.system_prompt}</pre>}
      </section>
    </div>
  )
}

function GenerationRows({ result }) {
  const groups = result.source_groups || []
  const generationCompleted = Boolean(result.summary?.query_generation_completed)
  const [openGroups, setOpenGroups] = useState(() => ({ unique_hook: true }))

  const toggleGroup = (key) => {
    setOpenGroups((current) => ({ ...current, [key]: !current[key] }))
  }

  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">
        {groups.map((group, groupIndex) => {
          const rows = group.fields || group.field_mappings || []
          const selectedCount = group.selected_field_count ?? rows.filter((row) => row.used_for_query || row.queries?.length).length
          const historicalCount = group.historical_field_count || 0
          const isOpen = Boolean(openGroups[group.key])
          return (
            <section className={`topic-source-group${isOpen ? ' is-open' : ''}`} key={group.key}>
              <button
                className="topic-source-group-toggle"
                type="button"
                onClick={() => toggleGroup(group.key)}
                aria-expanded={isOpen}
              >
                <span className="topic-source-index">来源 {groupIndex + 1}</span>
                <span className="topic-source-title">
                  <strong>{group.label}</strong>
                  <small>{group.source_description}</small>
                </span>
                <span className="topic-source-counts">
                  <b>{group.field_count ?? rows.length} 个真实字段</b>
                  <em>{selectedCount} 个用于生成</em>
                  {historicalCount > 0 && <i>{historicalCount} 个历史关系</i>}
                </span>
                <span className="topic-source-chevron">{isOpen ? '收起' : '展开'} <b>⌄</b></span>
              </button>
              <div className="topic-source-group-fields" hidden={!isOpen}>
                {rows.map((row) => {
                  const usedForQuery = row.used_for_query ?? Boolean(row.queries?.length)
                  return (
                    <article className={`topic-route-row${usedForQuery ? ' is-selected' : ''}`} key={row.field_key}>
                      <div className="topic-route-input">
                        <span>{row.field_label}</span>
                        {row.is_current === false && <span className="topic-history-tag">历史构建关系</span>}
                        <code>{row.field_path}</code>
                        <p>{row.field_value}</p>
                      </div>
                      <div className="topic-route-judgement">
                        {usedForQuery
                          ? <p>{row.judgement}</p>
                          : <p className="topic-unused-copy">{generationCompleted ? '本次未使用这个字段生成搜索词' : '尚未让大模型判断这个字段'}</p>}
                      </div>
                      <div className="topic-route-queries">
                        {usedForQuery
                          ? row.queries.map((query, index) => (
                            <div key={`${query}-${index}`}>
                              <b>{index + 1}</b>
                              <p>{query}</p>
                            </div>
                          ))
                          : <p className="topic-unused-copy">{generationCompleted ? '本次没有生成对应搜索词' : '点击“生成搜索词”后显示结果'}</p>}
                      </div>
                    </article>
                  )
                })}
              </div>
            </section>
          )
        })}
      </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 [sourceLoading, setSourceLoading] = 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 loadSourceData = useCallback(async (buildValue, topicValue, { signal } = {}) => {
    setSourceLoading(true)
    setError('')
    try {
      const payload = {
        topic_build_id: Number(buildValue),
        topic_id: topicValue ? Number(topicValue) : null,
        max_queries: 18,
      }
      const sourceResult = await getTopicTableSources(payload, { signal })
      setResult(sourceResult)
    } catch (e) {
      if (e.name !== 'AbortError') setError(e.message || '选题表完整数据读取失败')
    } finally {
      setSourceLoading(false)
    }
  }, [])

  useEffect(() => {
    const controller = new AbortController()
    loadSourceData(EXAMPLE.topicBuildId, EXAMPLE.topicId, { signal: controller.signal })
    return () => controller.abort()
  }, [loadSourceData])

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

      {error && <div className="manual-error topic-generation-error">{error}</div>}
      {sourceLoading && !result && <div className="topic-loading-card"><span />正在读取1229的完整选题表字段…</div>}
      {!result && !sourceLoading && !loading && <div className="topic-loading-card">填写选题表编号后，点击“载入真实示例”读取完整字段。</div>}
      {loading && <div className="topic-loading-card"><span />正在读取真实字段，并逐字段生成搜索词…</div>}
      {result && <GenerationRows result={result} />}
      {promptOpen && (
        <PromptModal
          payload={prompt}
          loading={promptLoading}
          error={promptError}
          onClose={() => setPromptOpen(false)}
        />
      )}
    </div>
  )
}
