import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import NodePickerModal, { getNodePath } from '../components/NodePickerModal.jsx'
import { useCategories } from '../contexts/CategoryContext.jsx'
import { useFiles } from '../contexts/FilesContext.jsx'
import { useSkills } from '../contexts/SkillsContext.jsx'

export default function CreateSkill() {
  const navigate = useNavigate()
  const { flat } = useCategories()
  const { getFilesUnder, files } = useFiles()
  const { createSkill } = useSkills()

  const [name, setName] = useState('')
  const [desc, setDesc] = useState('')
  const [creatorName, setCreatorName] = useState('')
  const [nodeId, setNodeId] = useState(null)
  const [pickerOpen, setPickerOpen] = useState(false)
  const [selectedFileIds, setSelectedFileIds] = useState([])
  const [submitBusy, setSubmitBusy] = useState(false)
  const [errorMsg, setErrorMsg] = useState('')

  // 节点变化后，候选文件 = 该节点（含子孙）下所有文件
  const candidateFiles = useMemo(() => {
    if (nodeId == null) return []
    return getFilesUnder(nodeId, flat)
  }, [nodeId, flat, getFilesUnder])

  const nodePath = nodeId != null ? getNodePath(nodeId, flat) : ''

  const handleNodeConfirm = (newId) => {
    setNodeId(newId)
    // 切换节点 → 默认全选该节点下所有文件作为上下文（用户可再取消）
    const next = newId != null ? getFilesUnder(newId, flat).map(f => f.id) : []
    setSelectedFileIds(next)
    setPickerOpen(false)
  }

  const toggleFile = (id) => {
    setSelectedFileIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }
  const selectAllFiles = () => setSelectedFileIds(candidateFiles.map(f => f.id))
  const clearAllFiles = () => setSelectedFileIds([])

  const trimmedName = name.trim()
  const trimmedCreator = creatorName.trim()
  const canSubmit = !!trimmedName && !!trimmedCreator && nodeId != null && !submitBusy

  const handleSave = async () => {
    if (!trimmedName) { setErrorMsg('请填写 Skill 名称'); return }
    if (!trimmedCreator) { setErrorMsg('请填写创建人姓名'); return }
    if (nodeId == null) { setErrorMsg('请选择关联流程节点（强制归位，不允许留作孤儿）'); return }
    const target = flat.find(n => n.id === nodeId)
    if (target && target.status === 'archived') {
      setErrorMsg('该流程节点已归档，不可作为新 Skill 的归属')
      return
    }
    setErrorMsg('')
    try {
      setSubmitBusy(true)
      const newId = await createSkill({
        name: trimmedName,
        desc: desc.trim(),
        node_id: nodeId,
        node_path: nodePath,
        source: 'create',
        creator_name: trimmedCreator,
      })
      if (!newId) { setErrorMsg('创建失败：后端未返回 Skill ID'); return }
      navigate(`/my-skills`)
    } catch (e) {
      const data = e?.response?.data
      let detail
      if (Array.isArray(data?.details) && data.details.length) {
        detail = data.details.join('；')
      } else {
        detail = data?.message || data?.error || e?.message || String(e)
      }
      setErrorMsg('创建失败：' + detail)
    } finally {
      setSubmitBusy(false)
    }
  }

  const handleReset = () => {
    setName(''); setDesc(''); setCreatorName(''); setNodeId(null); setSelectedFileIds([]); setErrorMsg('')
  }

  return (
    <div className="flex-1 overflow-auto p-8 max-w-3xl mx-auto w-full">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-[18px] font-semibold text-gray-900">创建 Skill</h1>
        <div className="text-[11px] text-gray-400">保存后进入 AI 创建对话：澄清 · 生成 · 评测 · 上架</div>
      </div>

      <div className="bg-white border border-gray-200 rounded-xl p-6 space-y-5">
        {/* 名称 */}
        <div>
          <label className="block text-[13px] text-gray-700 mb-1">名称 <span className="text-rose-500">*</span></label>
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="例如：流程访谈助手"
            className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400"
          />
        </div>

        {/* 描述 */}
        <div>
          <label className="block text-[13px] text-gray-700 mb-1">描述</label>
          <textarea
            value={desc}
            onChange={e => setDesc(e.target.value)}
            rows={3}
            placeholder="一句话说明 Skill 用途"
            className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400"
          />
        </div>

        {/* 创建人姓名（用户自填、必填） */}
        <div>
          <label className="block text-[13px] text-gray-700 mb-1">
            创建人姓名 <span className="text-rose-500">*</span>
            <span className="ml-2 text-[11px] text-gray-400">用于让运营/同事知道这个 Skill 是谁建的</span>
          </label>
          <input
            value={creatorName}
            onChange={e => setCreatorName(e.target.value)}
            placeholder="请填写您的真实姓名"
            maxLength={32}
            className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md focus:outline-none focus:border-brand-400"
          />
        </div>

        {/* 关联流程节点：可点击的伪 input（强制必填） */}
        <div>
          <label className="block text-[13px] text-gray-700 mb-1">
            关联流程节点 <span className="text-rose-500">*</span>
            <span className="ml-2 text-[11px] text-gray-400">所有 Skill 必须归属到流程架构下的某个节点，已归档节点不可选</span>
          </label>
          <div
            onClick={() => setPickerOpen(true)}
            className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-md cursor-pointer hover:border-brand-400 transition flex items-center justify-between gap-2 bg-white"
          >
            {nodeId != null ? (
              <span className="text-gray-800 truncate">
                <span className="text-brand-600 mr-1">⇲</span>{nodePath}
              </span>
            ) : (
              <span className="text-gray-400">点击从流程架构选择关联节点</span>
            )}
            <span className="text-gray-300 text-[12px] flex-shrink-0">{nodeId != null ? '更换' : '选择'} ▸</span>
          </div>
          {nodeId != null && (
            <div className="mt-1 text-[11px] text-gray-400">该节点（含子孙）下共 {candidateFiles.length} 个文件，可作为 Skill 上下文勾选</div>
          )}
        </div>

        {/* 上下文文件 */}
        {nodeId != null && (
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="block text-[13px] text-gray-700">上下文文件
                <span className="ml-2 text-[11px] text-gray-400">（架构 ↔ 文件 ↔ Skill 三者绑定）</span>
              </label>
              <div className="flex items-center gap-2 text-[11px]">
                <span className="text-gray-400">已选 {selectedFileIds.length} / {candidateFiles.length}</span>
                <button onClick={selectAllFiles} className="text-brand-600 hover:text-brand-700">全选</button>
                <span className="text-gray-200">|</span>
                <button onClick={clearAllFiles} className="text-gray-500 hover:text-gray-700">清空</button>
              </div>
            </div>

            {candidateFiles.length === 0 ? (
              <div className="border border-dashed border-gray-200 rounded-md p-6 text-center text-[12px] text-gray-400">
                该节点下还没有文件。可以先到「流程文件」页面给该节点上传文件，再回来勾选。
              </div>
            ) : (
              <div className="border border-gray-200 rounded-md max-h-[260px] overflow-y-auto scrollbar-thin">
                {candidateFiles.map(f => {
                  const checked = selectedFileIds.includes(f.id)
                  const path = getNodePath(f.category_id, flat)
                  return (
                    <label
                      key={f.id}
                      className={[
                        'flex items-start gap-2 px-3 py-2 text-[13px] cursor-pointer border-b border-gray-100 last:border-b-0',
                        checked ? 'bg-brand-50/40' : 'hover:bg-gray-50'
                      ].join(' ')}
                    >
                      <input
                        type="checkbox"
                        checked={checked}
                        onChange={() => toggleFile(f.id)}
                        className="mt-0.5 accent-brand-600"
                      />
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <span className="text-[10px] uppercase px-1 py-0.5 rounded bg-gray-100 text-gray-600">{f.ext}</span>
                          <span className="text-gray-800 truncate">{f.name}</span>
                        </div>
                        {f.summary && <div className="text-[11px] text-gray-500 mt-0.5 truncate">{f.summary}</div>}
                        <div className="text-[11px] text-gray-400 mt-0.5 truncate" title={path}>挂载于：{path}</div>
                      </div>
                    </label>
                  )
                })}
              </div>
            )}
          </div>
        )}

        {/* 操作 */}
        <div className="pt-2 flex items-center gap-2 justify-end border-t border-gray-100 -mx-6 px-6 pt-4">
          <button onClick={handleReset} disabled={submitBusy} className="px-3.5 py-1.5 text-[13px] rounded-md text-gray-600 border border-gray-200 hover:bg-gray-50 disabled:opacity-50">重置</button>
          <button onClick={() => navigate('/all-skills')} disabled={submitBusy} className="px-3.5 py-1.5 text-[13px] rounded-md text-gray-600 border border-gray-200 hover:bg-gray-50 disabled:opacity-50">取消</button>
          <button
            onClick={handleSave}
            disabled={!canSubmit}
            title={canSubmit ? '' : '请补全名称、创建人姓名、关联流程节点后再提交'}
            className="px-3.5 py-1.5 text-[13px] rounded-md text-white bg-brand-600 hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >{submitBusy ? '提交中…' : '保存并开始创建 →'}</button>
        </div>
      </div>

      {errorMsg && (
        <div className="mt-3 text-[12px] text-rose-600 bg-rose-50 border border-rose-200 rounded-md px-3 py-2">
          {errorMsg}
        </div>
      )}

      <NodePickerModal
        open={pickerOpen}
        initialNodeId={nodeId}
        onClose={() => setPickerOpen(false)}
        onConfirm={handleNodeConfirm}
      />
    </div>
  )
}
