import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowRight, Bot, FileText, Search, Send, Sparkles } from 'lucide-react'
import { getNodePath } from '../components/NodePickerModal.jsx'
import { useCategories } from '../contexts/CategoryContext.jsx'
import { useFiles } from '../contexts/FilesContext.jsx'
import { useSkills } from '../contexts/SkillsContext.jsx'

function scoreFile(file, query, flat) {
  const k = query.trim().toLowerCase()
  if (!k) return 0
  const path = getNodePath(file.category_id, flat)
  const fields = [
    [file.name, 4],
    [file.description || file.summary, 3],
    [path, 2],
    [file.content, 1],
  ]
  return fields.reduce((sum, [value, weight]) => {
    if (!value) return sum
    return String(value).toLowerCase().includes(k) ? sum + weight : sum
  }, 0)
}

function sameId(a, b) {
  if (a == null || b == null) return false
  return String(a) === String(b)
}

function relatedSkillCount(file, skills) {
  return skills.filter(s => sameId(s.node_id, file.category_id) || s.category_nodes?.some(n => sameId(n.id, file.category_id))).length
}

export default function KnowledgeQA() {
  const navigate = useNavigate()
  const { flat } = useCategories()
  const { files } = useFiles()
  const { skills } = useSkills()
  const [input, setInput] = useState('')
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '你可以问我某个流程怎么做、哪个 SOP 有依据、哪些流程文件适合转成 Skill。当前先基于标准知识对象的名称、描述、正文和流程路径做本地检索。',
      refs: [],
    }
  ])

  const recommended = useMemo(() => files.slice(0, 5), [files])

  function ask() {
    const q = input.trim()
    if (!q) return
    const ranked = files
      .map(file => ({ file, score: scoreFile(file, q, flat) }))
      .filter(x => x.score > 0)
      .sort((a, b) => b.score - a.score)
      .slice(0, 4)
      .map(x => x.file)

    const content = ranked.length
      ? [
          `我找到了 ${ranked.length} 份可能相关的流程文件。建议优先看排在前面的文件，因为它们的名称、描述或正文与问题更接近。`,
          '',
          ...ranked.map((file, idx) => {
            const path = getNodePath(file.category_id, flat) || file.node_path || '未绑定流程节点'
            return `${idx + 1}. ${file.name}\n   所属架构：${path}\n   摘要：${file.description || file.summary || '暂无描述'}\n   同节点 Skill：${relatedSkillCount(file, skills)} 个`
          }),
          '',
          '如果要继续，我建议打开最相关的流程文件，再从文件详情里生成或审查对应 Skill。'
        ].join('\n')
      : '没有找到明确匹配的流程文件。可以换一个业务对象、流程名称或制度关键词再试。'

    setMessages(prev => [
      ...prev,
      { role: 'user', content: q, refs: [] },
      { role: 'assistant', content, refs: ranked },
    ])
    setInput('')
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      ask()
    }
  }

  return (
    <div className="flex h-full overflow-hidden bg-gray-50">
      <aside className="hidden w-80 flex-shrink-0 border-r border-gray-200 bg-white p-4 lg:block">
        <div className="mb-4 flex items-center gap-2">
          <div className="grid h-8 w-8 place-items-center rounded-md bg-brand-50 text-brand-700">
            <Search size={16} />
          </div>
          <div>
            <div className="text-[14px] font-semibold text-gray-900">知识范围</div>
            <div className="text-[11px] text-gray-500">{files.length} 份流程文件</div>
          </div>
        </div>
        <div className="space-y-2">
          {recommended.map(file => (
            <button
              key={file.id}
              onClick={() => navigate(`/knowledge/files/${encodeURIComponent(file.id)}`)}
              className="w-full rounded-md border border-gray-200 px-3 py-2 text-left hover:border-brand-200 hover:bg-brand-50/40"
            >
              <div className="truncate text-[13px] font-medium text-gray-900">{file.name}</div>
              <div className="mt-1 line-clamp-2 text-[11px] leading-4 text-gray-500">{file.description || file.summary || '暂无描述'}</div>
            </button>
          ))}
        </div>
      </aside>

      <main className="flex min-w-0 flex-1 flex-col">
        <div className="border-b border-gray-200 bg-white px-6 py-4">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <div className="flex items-center gap-2 text-[12px] text-gray-500">
                <Sparkles size={14} className="text-brand-600" />
                <span>知识管理</span>
              </div>
              <h1 className="mt-1 text-[20px] font-semibold text-gray-950">知识问答</h1>
              <p className="mt-1 text-[13px] text-gray-500">围绕流程文件、SOP、制度知识提问，并把答案追溯到具体文件。</p>
            </div>
            <button
              onClick={() => navigate('/knowledge/files')}
              className="inline-flex h-9 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 text-[13px] text-gray-600 hover:bg-gray-50"
            >
              全部文件
              <ArrowRight size={14} />
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          <div className="mx-auto flex max-w-4xl flex-col gap-4">
            {messages.map((msg, idx) => (
              <div key={idx} className={msg.role === 'user' ? 'flex justify-end' : 'flex justify-start'}>
                <div className={[
                  'max-w-[86%] rounded-lg px-4 py-3 text-[13px] leading-6 shadow-sm',
                  msg.role === 'user'
                    ? 'bg-brand-600 text-white'
                    : 'border border-gray-200 bg-white text-gray-700'
                ].join(' ')}>
                  {msg.role === 'assistant' && (
                    <div className="mb-2 flex items-center gap-2 text-[12px] font-medium text-gray-900">
                      <Bot size={14} />
                      知识助手
                    </div>
                  )}
                  <div className="whitespace-pre-wrap">{msg.content}</div>
                  {msg.refs?.length > 0 && (
                    <div className="mt-3 grid gap-2">
                      {msg.refs.map(file => (
                        <button
                          key={file.id}
                          onClick={() => navigate(`/knowledge/files/${encodeURIComponent(file.id)}`)}
                          className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-left text-gray-700 hover:bg-white"
                        >
                          <FileText size={15} className="text-gray-400" />
                          <span className="min-w-0 flex-1 truncate">{file.name}</span>
                          <ArrowRight size={14} className="text-gray-400" />
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="border-t border-gray-200 bg-white px-6 py-4">
          <div className="mx-auto flex max-w-4xl items-end gap-3">
            <textarea
              rows={2}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="例如：员工报销流程怎么审查？哪些文件可以转成 Skill？"
              className="min-h-[44px] flex-1 resize-none rounded-lg border border-gray-200 px-3 py-2 text-[13px] outline-none focus:border-brand-400"
            />
            <button
              onClick={ask}
              disabled={!input.trim()}
              className="grid h-11 w-11 place-items-center rounded-lg bg-brand-600 text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
            >
              <Send size={17} />
            </button>
          </div>
        </div>
      </main>
    </div>
  )
}
