import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  ArrowRight,
  Bot,
  CheckCircle2,
  CircleDot,
  Database,
  FilePlus2,
  FileText,
  GitBranch,
  LayoutGrid,
  Library,
  ListFilter,
  Search,
  Send,
  Sparkles,
  Workflow,
} from 'lucide-react'
import CategoryTree from '../components/CategoryTree.jsx'
import { getNodePath } from '../components/NodePickerModal.jsx'
import { useAuth } from '../contexts/AuthContext.jsx'
import { useCategories } from '../contexts/CategoryContext.jsx'
import { useFiles } from '../contexts/FilesContext.jsx'
import { useSkills } from '../contexts/SkillsContext.jsx'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'

const STATUS = {
  draft: { label: '草稿', cls: 'bg-gray-100 text-gray-600 ring-gray-200' },
  review: { label: '审查中', cls: 'bg-amber-50 text-amber-700 ring-amber-200' },
  submitted: { label: '已提报', cls: 'bg-sky-50 text-sky-700 ring-sky-200' },
  published: { label: '已入库', cls: 'bg-emerald-50 text-emerald-700 ring-emerald-200' },
  archived: { label: '已归档', cls: 'bg-slate-100 text-slate-500 ring-slate-200' },
}

const STATUS_ORDER = ['all', 'draft', 'review', 'submitted', 'published']

const WORKFLOW = [
  { key: 'draft', label: '创建', caption: '草稿' },
  { key: 'review', label: '审查', caption: '待确认' },
  { key: 'submitted', label: '提报', caption: '待批准' },
  { key: 'published', label: '入库', caption: '可复用' },
]

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

function formatTime(iso) {
  if (!iso) return '-'
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return '-'
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

function StatusBadge({ status }) {
  const conf = STATUS[status] || STATUS.draft
  return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] ring-1 ${conf.cls}`}>{conf.label}</span>
}

function isOwnedBy(file, user) {
  if (!user) return false
  if (file.owner_email && user.email && file.owner_email === user.email) return true
  if (file.owner_phone && user.phone && file.owner_phone === user.phone) return true
  return file.source === 'seed' || file.uploader === '当前用户'
}

function relatedSkills(file, skills) {
  return skills.filter(skill => {
    if ((file.related_skill_ids || []).some(id => sameId(id, skill.id))) return true
    if (skill.source_file_id && sameId(skill.source_file_id, file.id)) return true
    if (skill.node_id && file.category_id && sameId(skill.node_id, file.category_id)) return true
    const node = skill.category_nodes?.[0]
    return node?.id && file.category_id && sameId(node.id, file.category_id)
  })
}

function nextFileAction(file, updateFile, openOverlay) {
  if (file.status === 'draft') {
    return { label: '发起审查', onClick: () => updateFile(file.id, { status: 'review' }) }
  }
  if (file.status === 'review') {
    return { label: '审批提报', onClick: () => updateFile(file.id, { status: 'submitted' }) }
  }
  if (file.status === 'submitted') {
    return { label: '入库', onClick: () => updateFile(file.id, { status: 'published' }) }
  }
  return { label: '转 Skill', onClick: () => openOverlay('create', { sourceFileId: file.id }) }
}

function CreateFileModal({ open, mode, initialCategoryId, onClose, onSubmit }) {
  const { flat } = useCategories()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [content, setContent] = useState('')
  const [categoryId, setCategoryId] = useState(initialCategoryId || '')

  useEffect(() => {
    if (open) setCategoryId(initialCategoryId || '')
  }, [open, initialCategoryId])

  if (!open) return null

  const activeNodes = flat.filter(n => (n.status || 'active') === 'active')
  const title = mode === 'ai' ? 'AI 创建流程文件' : '登记流程文件'

  function reset() {
    setName('')
    setDescription('')
    setContent('')
    setCategoryId(initialCategoryId || '')
  }

  function submit() {
    if (!name.trim()) {
      window.alert('请填写文件名称')
      return
    }
    if (!categoryId) {
      window.alert('请选择所属流程节点')
      return
    }
    const defaultContent = [
      `# ${name.trim()}`,
      '',
      '## 一、目的',
      description.trim() || '说明本流程存在的业务目的和管理价值。',
      '',
      '## 二、适用范围',
      '待补充。',
      '',
      '## 三、输入/输出',
      '| 类型 | 内容 | 说明 |',
      '|---|---|---|',
      '| 输入 | 待补充 | 触发流程的事件、指令或材料 |',
      '| 输出 | 待补充 | 流程完成后的交付物或结果 |',
      '',
      '## 四、关键活动',
      '待补充关键活动、角色职责、控制点和办理时限。',
      '',
      '## 五、流程图',
      '```mermaid',
      'graph TD',
      '  A[开始] --> B[关键活动]',
      '  B --> C[结束]',
      '```',
    ].join('\n')
    onSubmit({
      name: name.trim(),
      ext: 'md',
      description: description.trim(),
      summary: description.trim(),
      content: content.trim() || defaultContent,
      category_id: categoryId,
      status: mode === 'ai' ? 'draft' : 'published',
      source: mode === 'ai' ? 'ai-created' : 'manual',
    })
    reset()
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4" onClick={onClose}>
      <div className="w-full max-w-2xl overflow-hidden rounded-lg bg-white shadow-2xl" onClick={e => e.stopPropagation()}>
        <div className="flex items-start justify-between border-b border-gray-100 px-5 py-4">
          <div>
            <div className="text-[15px] font-semibold text-gray-900">{title}</div>
            <div className="mt-0.5 text-[12px] text-gray-500">
              使用标准知识对象保存：名称、描述、正文、流程节点。后续可直接转为 Skill 上下文。
            </div>
          </div>
          <button onClick={onClose} className="rounded-md px-2 py-1 text-gray-400 hover:bg-gray-50 hover:text-gray-700">×</button>
        </div>
        <div className="max-h-[68vh] space-y-4 overflow-y-auto px-5 py-4">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-[1.2fr_0.8fr]">
            <div>
              <label className="mb-1 block text-[12px] text-gray-600">文件名称</label>
              <input
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="例如：员工费用报销流程"
                className="h-10 w-full rounded-md border border-gray-200 px-3 text-[13px] outline-none focus:border-brand-400"
              />
            </div>
            <div>
              <label className="mb-1 block text-[12px] text-gray-600">所属流程节点</label>
              <select
                value={categoryId}
                onChange={e => setCategoryId(e.target.value)}
                className="h-10 w-full rounded-md border border-gray-200 px-3 text-[13px] outline-none focus:border-brand-400"
              >
                <option value="">选择流程节点</option>
                {activeNodes.map(n => (
                  <option key={n.id} value={n.id}>{n.path || n.label}</option>
                ))}
              </select>
            </div>
          </div>
          <div>
            <label className="mb-1 block text-[12px] text-gray-600">描述</label>
            <textarea
              value={description}
              onChange={e => setDescription(e.target.value)}
              rows={3}
              placeholder="说明文件解决什么问题、适用什么场景、谁会使用。"
              className="w-full resize-none rounded-md border border-gray-200 px-3 py-2 text-[13px] outline-none focus:border-brand-400"
            />
          </div>
          <div>
            <label className="mb-1 block text-[12px] text-gray-600">正文内容</label>
            <textarea
              value={content}
              onChange={e => setContent(e.target.value)}
              rows={9}
              placeholder="可粘贴流程文件正文；留空时会生成一份标准流程文件骨架。"
              className="w-full resize-none rounded-md border border-gray-200 px-3 py-2 font-mono text-[12px] leading-5 outline-none focus:border-brand-400"
            />
          </div>
        </div>
        <div className="flex items-center justify-end gap-2 border-t border-gray-100 bg-gray-50 px-5 py-3">
          <button onClick={onClose} className="rounded-md border border-gray-200 bg-white px-3 py-1.5 text-[13px] text-gray-600 hover:bg-gray-50">取消</button>
          <button onClick={submit} className="rounded-md bg-brand-600 px-3.5 py-1.5 text-[13px] text-white hover:bg-brand-700">保存文件</button>
        </div>
      </div>
    </div>
  )
}

export default function KnowledgeFiles({ mode = 'all' }) {
  const navigate = useNavigate()
  const { openOverlay } = useChatOverlay()
  const { user } = useAuth()
  const { flat } = useCategories()
  const { files, getFilesUnder, addFile, updateFile } = useFiles()
  const { skills } = useSkills()
  const [selectedNode, setSelectedNode] = useState(null)
  const [query, setQuery] = useState('')
  const [status, setStatus] = useState('all')
  const [view, setView] = useState('architecture')
  const [modalMode, setModalMode] = useState(null)

  const nodeId = selectedNode?.id || null
  const filesInScope = useMemo(() => nodeId ? getFilesUnder(nodeId, flat) : files, [files, nodeId, getFilesUnder, flat])

  const filtered = useMemo(() => {
    const k = query.trim().toLowerCase()
    return filesInScope.filter(file => {
      if (mode === 'mine' && !isOwnedBy(file, user)) return false
      if (status !== 'all' && file.status !== status) return false
      if (!k) return true
      return [file.name, file.description, file.summary, file.content, getNodePath(file.category_id, flat)]
        .filter(Boolean)
        .some(v => String(v).toLowerCase().includes(k))
    })
  }, [filesInScope, mode, query, status, user, flat])

  const stats = useMemo(() => {
    const source = mode === 'mine' ? files.filter(f => isOwnedBy(f, user)) : files
    return {
      total: source.length,
      draft: source.filter(f => f.status === 'draft').length,
      published: source.filter(f => f.status === 'published').length,
      review: source.filter(f => f.status === 'review').length,
      submitted: source.filter(f => f.status === 'submitted').length,
    }
  }, [files, mode, user])

  function handleCreate(payload) {
    addFile({
      ...payload,
      owner: user?.name || user?.email || '当前用户',
      owner_email: user?.email || '',
      owner_phone: user?.phone || '',
      uploader: user?.name || user?.email || '当前用户',
      node_path: getNodePath(payload.category_id, flat),
    })
    setModalMode(null)
  }

  const title = mode === 'mine' ? '我的文件' : '全部文件'
  const subtitle = mode === 'mine'
    ? '我负责维护的流程文件、SOP 和制度知识。'
    : '企业流程文件的统一入口，共享同一套流程架构。'

  return (
    <div className="flex h-full overflow-hidden bg-gray-50">
      {view === 'architecture' && (
        <div className="hidden lg:block">
          <CategoryTree selectedId={nodeId} onSelect={setSelectedNode} />
        </div>
      )}

      <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
        <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 className="min-w-0">
              <div className="flex items-center gap-2 text-[12px] text-gray-500">
                <Library size={14} className="text-brand-600" />
                <span>知识管理</span>
                {selectedNode && <span className="truncate text-gray-400">/ {selectedNode.label}</span>}
              </div>
              <h1 className="mt-1 text-[20px] font-semibold text-gray-950">{title}</h1>
              <p className="mt-1 text-[13px] text-gray-500">{subtitle}</p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setView(view === 'architecture' ? 'library' : 'architecture')}
                title={view === 'architecture' ? '文件视图' : '架构视图'}
                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 transition hover:bg-gray-50 max-sm:w-9 max-sm:justify-center max-sm:px-0"
              >
                {view === 'architecture' ? <LayoutGrid size={15} /> : <GitBranch size={15} />}
                <span className="whitespace-nowrap max-sm:hidden">{view === 'architecture' ? '文件视图' : '架构视图'}</span>
              </button>
              <button
                onClick={() => setModalMode('manual')}
                title="登记文件"
                className="inline-flex h-9 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 text-[13px] text-gray-700 transition hover:bg-gray-50 max-sm:w-9 max-sm:justify-center max-sm:px-0"
              >
                <FileText size={15} />
                <span className="whitespace-nowrap max-sm:hidden">登记文件</span>
              </button>
              <button
                onClick={() => setModalMode('ai')}
                title="AI 创建"
                className="inline-flex h-9 items-center gap-1.5 rounded-md bg-gray-950 px-3 text-[13px] text-white transition hover:bg-gray-800 max-sm:w-9 max-sm:justify-center max-sm:px-0"
              >
                <Sparkles size={15} />
                <span className="whitespace-nowrap max-sm:hidden">AI 创建</span>
              </button>
            </div>
          </div>

          <div className="mt-3 flex flex-wrap items-center gap-2">
            <SummaryPill label="总数" value={stats.total} icon={<FileText size={14} />} />
            <SummaryPill label="草稿" value={stats.draft} icon={<FilePlus2 size={14} />} />
            <SummaryPill label="审查中" value={stats.review} icon={<CheckCircle2 size={14} />} />
            <SummaryPill label="已提报" value={stats.submitted} icon={<Send size={14} />} />
            <SummaryPill label="已入库" value={stats.published} icon={<Database size={14} />} />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-5 lg:p-6">
          <section className="mb-4 rounded-lg border border-gray-200 bg-white p-4 shadow-sm shadow-slate-200/40">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="flex min-w-0 items-center gap-3">
                <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md bg-emerald-50 text-emerald-700 ring-1 ring-emerald-100">
                <Bot size={18} />
                </div>
                <div className="min-w-0">
                  <div className="text-[14px] font-semibold text-gray-950">AI 指令台</div>
                  <div className="truncate text-[12px] text-gray-500">
                    {selectedNode ? `当前范围：${selectedNode.label}` : '全企业流程知识'}
                  </div>
                </div>
              </div>
              <button
                onClick={() => navigate('/knowledge/qa')}
                className="inline-flex h-9 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 text-[13px] text-gray-700 transition hover:bg-gray-50"
              >
                知识问答
                <ArrowRight size={14} />
              </button>
            </div>
            <div className="mt-4 grid grid-cols-1 gap-3 xl:grid-cols-[1fr_520px]">
              <div className="flex min-w-0 items-center gap-2 rounded-md border border-gray-200 bg-white px-3 ring-1 ring-transparent transition focus-within:border-brand-300 focus-within:ring-brand-100">
                <Search size={16} className="flex-shrink-0 text-gray-400" />
                <input
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder="搜索流程、SOP、制度或业务对象"
                  className="h-10 flex-1 border-0 text-[13px] outline-none"
                />
              </div>
              <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                <CommandAction icon={<Sparkles size={15} />} label="起草文件" onClick={() => setModalMode('ai')} />
                <CommandAction icon={<CheckCircle2 size={15} />} label="审查草稿" onClick={() => setStatus('draft')} />
                <CommandAction icon={<Send size={15} />} label="审批提报" onClick={() => setStatus('review')} />
                <CommandAction icon={<Workflow size={15} />} label="转 Skill" onClick={() => setStatus('published')} dark />
              </div>
            </div>
            <div className="mt-4 grid grid-cols-2 gap-2 md:grid-cols-4">
              {WORKFLOW.map((step, idx) => (
                <WorkflowStep
                  key={step.key}
                  step={idx + 1}
                  label={step.label}
                  caption={step.caption}
                  count={stats[step.key] || 0}
                  active={status === step.key}
                  onClick={() => setStatus(step.key)}
                />
              ))}
            </div>
          </section>

          <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
            <div className="text-[13px] text-gray-500">
              当前显示 <span className="font-medium text-gray-900">{filtered.length}</span> 份文件
            </div>
            <div className="flex flex-wrap items-center gap-1">
              <ListFilter size={15} className="mr-1 text-gray-400" />
              {STATUS_ORDER.map(key => (
                <button
                  key={key}
                  onClick={() => setStatus(key)}
                  className={[
                    'h-8 rounded-md px-2.5 text-[12px] transition',
                    status === key ? 'bg-gray-950 text-white' : 'text-gray-600 hover:bg-white'
                  ].join(' ')}
                >
                  {key === 'all' ? '全部状态' : STATUS[key].label}
                </button>
              ))}
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="rounded-lg border border-dashed border-gray-300 bg-white p-12 text-center">
              <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-lg bg-gray-50 text-gray-400">
                <FileText size={22} />
              </div>
              <div className="text-[14px] font-medium text-gray-800">还没有匹配的流程文件</div>
              <div className="mt-1 text-[12px] text-gray-500">可以登记文件，或用 AI 起草标准流程文件骨架。</div>
              <div className="mt-4 flex justify-center gap-2">
                <button onClick={() => setModalMode('manual')} className="rounded-md border border-gray-200 bg-white px-3 py-1.5 text-[13px] text-gray-700 hover:bg-gray-50">登记文件</button>
                <button onClick={() => setModalMode('ai')} className="rounded-md bg-gray-950 px-3 py-1.5 text-[13px] text-white hover:bg-gray-800">AI 起草</button>
              </div>
            </div>
          ) : (
            <div className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm shadow-slate-200/40">
              <div className="hidden grid-cols-[minmax(0,1.65fr)_minmax(180px,1fr)_92px_92px_110px_148px] gap-3 border-b border-gray-100 bg-gray-50 px-4 py-2.5 text-[12px] font-medium text-gray-500 xl:grid">
                <div>文件</div>
                <div>流程路径</div>
                <div>状态</div>
                <div>Skill</div>
                <div>更新</div>
                <div className="text-right">动作</div>
              </div>
              {filtered.map(file => {
                const skillsForFile = relatedSkills(file, skills)
                const path = getNodePath(file.category_id, flat) || file.node_path || '未绑定流程节点'
                const action = nextFileAction(file, updateFile, openOverlay)
                return (
                  <div
                    key={file.id}
                    className="grid grid-cols-1 gap-3 border-b border-gray-100 px-4 py-4 transition last:border-b-0 hover:bg-gray-50/80 xl:grid-cols-[minmax(0,1.65fr)_minmax(180px,1fr)_92px_92px_110px_148px] xl:items-center"
                  >
                    <div className="min-w-0">
                      <div className="mb-1.5 flex flex-wrap items-center gap-2">
                        <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[11px] uppercase text-gray-500">{file.ext}</span>
                        <span className="text-[11px] text-gray-400">{file.version}</span>
                      </div>
                      <div className="flex min-w-0 items-start justify-between gap-3 xl:block">
                        <button
                          onClick={() => navigate(`/knowledge/files/${encodeURIComponent(file.id)}`)}
                          className="block truncate text-left text-[15px] font-semibold text-gray-950 hover:text-brand-700"
                          title={file.name}
                        >
                          {file.name}
                        </button>
                        <div className="xl:hidden"><StatusBadge status={file.status} /></div>
                      </div>
                      <p className="mt-1 line-clamp-2 text-[13px] leading-5 text-gray-600">{file.description || '暂无描述'}</p>
                    </div>
                    <div className="flex min-w-0 items-center gap-2 text-[12px] text-gray-500">
                      <GitBranch size={14} className="flex-shrink-0 text-gray-400" />
                      <span className="truncate" title={path}>{path}</span>
                    </div>
                    <div className="hidden xl:block"><StatusBadge status={file.status} /></div>
                    <div className="flex items-center gap-1.5 text-[12px] text-gray-600">
                      <CircleDot size={13} className="text-gray-300" />
                      {skillsForFile.length} 个
                    </div>
                    <div className="text-[12px] text-gray-500">
                      <div>{formatTime(file.updated_at)}</div>
                      <div className="mt-0.5 truncate text-[11px] text-gray-400">{file.owner || file.uploader || '未指定'}</div>
                    </div>
                    <div className="flex items-center justify-start gap-2 xl:justify-end">
                      <button
                        onClick={() => navigate(`/knowledge/files/${encodeURIComponent(file.id)}`)}
                        className="h-8 rounded-md border border-gray-200 bg-white px-2.5 text-[12px] text-gray-700 hover:bg-gray-50"
                      >
                        打开
                      </button>
                      <button
                        onClick={action.onClick}
                        className="inline-flex h-8 items-center gap-1 rounded-md bg-gray-950 px-2.5 text-[12px] text-white hover:bg-gray-800"
                      >
                        {action.label}
                        <ArrowRight size={13} />
                      </button>
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>

      <CreateFileModal
        open={!!modalMode}
        mode={modalMode}
        initialCategoryId={nodeId}
        onClose={() => setModalMode(null)}
        onSubmit={handleCreate}
      />
    </div>
  )
}

function SummaryPill({ label, value, icon }) {
  return (
    <div className="inline-flex h-8 items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-2.5 text-[12px] text-gray-600">
      <span className="text-gray-400">{icon}</span>
      <span>{label}</span>
      <span className="font-semibold text-gray-950">{value}</span>
    </div>
  )
}

function CommandAction({ icon, label, onClick, dark = false }) {
  return (
    <button
      onClick={onClick}
      className={[
        'inline-flex h-10 items-center justify-center gap-1.5 rounded-md px-3 text-[13px] font-medium transition',
        dark
          ? 'bg-gray-950 text-white hover:bg-gray-800'
          : 'border border-gray-200 bg-white text-gray-700 hover:border-gray-300 hover:bg-gray-50'
      ].join(' ')}
    >
      {icon}
      <span className="truncate whitespace-nowrap">{label}</span>
    </button>
  )
}

function WorkflowStep({ step, label, caption, count, active, onClick }) {
  return (
    <button
      onClick={onClick}
      className={[
        'flex min-h-[66px] items-center gap-3 rounded-md border px-3 text-left transition',
        active
          ? 'border-gray-900 bg-gray-950 text-white'
          : 'border-gray-200 bg-gray-50 text-gray-700 hover:bg-white'
      ].join(' ')}
    >
      <span className={[
        'grid h-7 w-7 flex-shrink-0 place-items-center rounded-full text-[12px] font-semibold',
        active ? 'bg-white text-gray-950' : 'bg-white text-gray-500 ring-1 ring-gray-200'
      ].join(' ')}>
        {step}
      </span>
      <span className="min-w-0 flex-1">
        <span className="block whitespace-nowrap text-[13px] font-semibold">{label}</span>
        <span className={active ? 'block text-[11px] text-white/70 max-sm:hidden' : 'block text-[11px] text-gray-500 max-sm:hidden'}>{caption}</span>
      </span>
      <span className={active ? 'text-[18px] font-semibold text-white' : 'text-[18px] font-semibold text-gray-950'}>{count}</span>
    </button>
  )
}
