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

const JSON_EXAMPLE = `[
  "符号 视频 灵感 怎么做",
  "符号 视频 灵感 有哪些",
  "叙事体裁 视频 灵感 为什么"
]`

function normalizeJsonQueries(value) {
  if (Array.isArray(value)) return value
  if (!value || typeof value !== 'object') return []
  if (Array.isArray(value.queries)) return value.queries
  if (Array.isArray(value.families)) {
    return value.families.flatMap((family) => (
      Array.isArray(family?.items)
        ? family.items.map((item) => ({
          ...item,
          metadata: {
            ...(item.metadata || {}),
            source_family_key: family.key || family.family_key,
            source_family_name: family.name || family.title,
          },
        }))
        : []
    ))
  }
  if (value.query || value.query_text) return [value]
  return []
}

function queryLabel(value) {
  if (typeof value === 'string') return value.trim()
  if (value && typeof value === 'object') return String(value.query_text || value.query || '').trim()
  return ''
}

export default function ManualQueryModal({ mode, onClose, onSubmitted }) {
  const [text, setText] = useState('')
  const [jsonQueries, setJsonQueries] = useState([])
  const [fileName, setFileName] = useState('')
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const queries = useMemo(() => {
    if (mode === 'json') return jsonQueries
    return text.split('\n').map((line) => line.trim()).filter(Boolean)
  }, [jsonQueries, mode, text])
  const previews = queries.map(queryLabel).filter(Boolean).slice(0, 5)

  const onFileChange = async (event) => {
    const file = event.target.files?.[0]
    if (!file) return
    setError('')
    setFileName(file.name)
    try {
      const raw = await file.text()
      const parsed = JSON.parse(raw)
      const nextQueries = normalizeJsonQueries(parsed).filter((item) => queryLabel(item))
      setJsonQueries(nextQueries)
      if (!nextQueries.length) setError('这个 JSON 里没有识别到 query')
    } catch {
      setJsonQueries([])
      setError('JSON 解析失败')
    }
  }

  const onSubmit = async () => {
    const clean = queries.filter((item) => queryLabel(item))
    if (!clean.length) {
      setError('请先输入或上传 query')
      return
    }
    setSubmitting(true)
    setError('')
    try {
      const result = await submitManualQueryBatch({ queries: clean })
      await onSubmitted?.(result)
    } catch (e) {
      setError(e.message || '提交失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="manual-modal-mask" onClick={onClose}>
      <div className="manual-modal-panel" onClick={(event) => event.stopPropagation()}>
        <div className="manual-modal-head">
          <div>
            <h2>{mode === 'json' ? '上传 JSON' : '手动输入'}</h2>
            <p>提交后会创建手动 query 批次，并在后台跑搜索、初筛、解构和 payload dry-run。</p>
          </div>
          <button className="manual-close" type="button" onClick={onClose}>×</button>
        </div>

        {mode === 'json' ? (
          <>
            <label className="manual-upload">
              <input accept=".json,application/json" type="file" onChange={onFileChange} />
              <span>{fileName || '选择 JSON 文件'}</span>
            </label>
            <div className="manual-json-example">
              <div className="manual-json-example-title">JSON 格式案例</div>
              <pre>{JSON_EXAMPLE}</pre>
            </div>
          </>
        ) : (
          <textarea
            className="manual-textarea"
            placeholder="一行一个 query，例如：&#10;符号 视频 灵感 怎么做&#10;叙事体裁 视频 灵感 有哪些"
            value={text}
            onChange={(event) => setText(event.target.value)}
          />
        )}

        <div className="manual-preview">
          <strong>识别到 {queries.length} 条</strong>
          {previews.length ? (
            <ul>
              {previews.map((item, index) => <li key={`${item}-${index}`}>{item}</li>)}
            </ul>
          ) : (
            <span>暂无预览</span>
          )}
        </div>

        {error && <div className="manual-error">{error}</div>}

        <div className="manual-actions">
          <button className="manual-secondary" type="button" onClick={onClose}>取消</button>
          <button className="manual-primary" disabled={submitting} type="button" onClick={onSubmit}>
            {submitting ? '提交中...' : '提交并后台运行'}
          </button>
        </div>
      </div>
    </div>
  )
}
