import { useMemo } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft, Bot, CheckCircle2, FileText, GitBranch, Send, Sparkles, Workflow } from 'lucide-react'
import { getNodePath } from '../components/NodePickerModal.jsx'
import StatusBadge from '../components/StatusBadge.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 FILE_STATUS = {
  draft: '草稿',
  review: '审查中',
  submitted: '已提报',
  published: '已入库',
  archived: '已归档',
}

const STEPS = [
  { key: 'draft', label: '创建' },
  { key: 'review', label: '审查' },
  { key: 'submitted', label: '提报' },
  { key: 'published', label: '入库' },
]

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

function fileRelatedSkills(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 && sameId(skill.node_id, file.category_id)) return true
    return skill.category_nodes?.some(n => sameId(n.id, file.category_id))
  })
}

export default function ProcessFileDetail() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { openOverlay } = useChatOverlay()
  const { flat } = useCategories()
  const { findFile, updateFile } = useFiles()
  const { skills } = useSkills()

  const file = findFile(id)
  const related = useMemo(() => file ? fileRelatedSkills(file, skills) : [], [file, skills])

  if (!file) {
    return (
      <div className="flex h-full items-center justify-center bg-gray-50 p-6">
        <div className="rounded-lg border border-gray-200 bg-white px-8 py-7 text-center">
          <div className="text-[15px] font-medium text-gray-900">没有找到这份流程文件</div>
          <button onClick={() => navigate('/knowledge/files')} className="mt-4 rounded-md bg-brand-600 px-3 py-1.5 text-[13px] text-white">
            返回文件库
          </button>
        </div>
      </div>
    )
  }

  const path = getNodePath(file.category_id, flat) || file.node_path || '未绑定流程节点'
  const currentStepIndex = Math.max(0, STEPS.findIndex(s => s.key === file.status))

  return (
    <div className="h-full overflow-y-auto bg-gray-50">
      <div className="border-b border-gray-200 bg-white px-6 py-4">
        <button
          onClick={() => navigate('/knowledge/files')}
          className="mb-3 inline-flex items-center gap-1.5 text-[13px] text-gray-500 hover:text-gray-900"
        >
          <ArrowLeft size={15} />
          返回知识管理
        </button>
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="min-w-0">
            <div className="mb-2 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="rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] text-emerald-700">{FILE_STATUS[file.status] || '草稿'}</span>
              <span className="text-[11px] text-gray-400">{file.version}</span>
            </div>
            <h1 className="text-[22px] font-semibold text-gray-950">{file.name}</h1>
            <div className="mt-2 flex items-center gap-1.5 text-[13px] text-gray-500">
              <GitBranch size={14} />
              <span className="truncate">{path}</span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => updateFile(file.id, { status: 'review' })}
              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"
            >
              <CheckCircle2 size={15} />
              发起审查
            </button>
            <button
              onClick={() => updateFile(file.id, { status: 'submitted' })}
              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"
            >
              <Send size={15} />
              审批提报
            </button>
            <button
              onClick={() => openOverlay('create', { sourceFileId: file.id })}
              className="inline-flex h-9 items-center gap-1.5 rounded-md bg-gray-900 px-3 text-[13px] text-white hover:bg-gray-800"
            >
              <Sparkles size={15} />
              基于文件创建 Skill
            </button>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 p-6 xl:grid-cols-[1fr_360px]">
        <div className="space-y-6">
          <section className="rounded-lg border border-gray-200 bg-white">
            <div className="border-b border-gray-100 px-5 py-4">
              <div className="text-[14px] font-semibold text-gray-900">标准知识对象</div>
              <div className="mt-0.5 text-[12px] text-gray-500">Skill 创建和知识问答都应读取这些结构化字段。</div>
            </div>
            <div className="divide-y divide-gray-100">
              <Field label="名称" value={file.name} />
              <Field label="描述" value={file.description || '暂无描述'} />
              <Field label="流程路径" value={path} />
              <Field label="维护人" value={file.owner || file.uploader || '未指定'} />
            </div>
          </section>

          <section className="rounded-lg border border-gray-200 bg-white">
            <div className="flex items-center justify-between border-b border-gray-100 px-5 py-4">
              <div>
                <div className="text-[14px] font-semibold text-gray-900">正文内容</div>
                <div className="mt-0.5 text-[12px] text-gray-500">当前先以 Markdown / Mermaid 保存，后续可接企业文件系统。</div>
              </div>
              <FileText size={18} className="text-gray-400" />
            </div>
            <pre className="max-h-[560px] overflow-auto whitespace-pre-wrap px-5 py-4 text-[13px] leading-6 text-gray-700">
              {file.content || '暂无正文内容'}
            </pre>
          </section>
        </div>

        <aside className="space-y-4">
          <section className="rounded-lg border border-gray-200 bg-white p-4">
            <div className="mb-4 flex items-center gap-2">
              <Workflow size={16} className="text-brand-600" />
              <div className="text-[14px] font-semibold text-gray-900">文件生命周期</div>
            </div>
            <div className="space-y-3">
              {STEPS.map((step, idx) => {
                const done = idx <= currentStepIndex
                return (
                  <div key={step.key} className="flex items-center gap-3">
                    <div className={`grid h-7 w-7 place-items-center rounded-full text-[12px] ${done ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-400'}`}>
                      {idx + 1}
                    </div>
                    <div className={done ? 'text-[13px] font-medium text-gray-900' : 'text-[13px] text-gray-500'}>{step.label}</div>
                  </div>
                )
              })}
            </div>
            <button
              onClick={() => updateFile(file.id, { status: 'published' })}
              className="mt-4 w-full rounded-md bg-brand-600 px-3 py-2 text-[13px] text-white hover:bg-brand-700"
            >
              标记为已入库
            </button>
          </section>

          <section className="rounded-lg border border-gray-200 bg-white p-4">
            <div className="mb-3 flex items-center gap-2">
              <Bot size={16} className="text-gray-700" />
              <div className="text-[14px] font-semibold text-gray-900">关联 Skill</div>
            </div>
            {related.length === 0 ? (
              <div className="rounded-md border border-dashed border-gray-300 bg-gray-50 px-3 py-4 text-[12px] text-gray-500">
                暂无已关联 Skill。建议先基于这份流程文件生成候选 Skill。
              </div>
            ) : (
              <div className="space-y-2">
                {related.slice(0, 5).map(skill => (
                  <button
                    key={skill.id}
                    onClick={() => navigate('/all-skills')}
                    className="w-full rounded-md border border-gray-200 px-3 py-2 text-left hover:bg-gray-50"
                  >
                    <div className="truncate text-[13px] font-medium text-gray-900">{skill.title || skill.name}</div>
                    <div className="mt-1 flex items-center justify-between gap-2">
                      <span className="truncate text-[11px] text-gray-500">{skill.desc || skill.description || '暂无描述'}</span>
                      <StatusBadge status={skill.status} />
                    </div>
                  </button>
                ))}
              </div>
            )}
          </section>
        </aside>
      </div>
    </div>
  )
}

function Field({ label, value }) {
  return (
    <div className="grid grid-cols-[120px_1fr] gap-4 px-5 py-3 text-[13px]">
      <div className="text-gray-400">{label}</div>
      <div className="min-w-0 whitespace-pre-wrap text-gray-800">{value}</div>
    </div>
  )
}
