import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { FolderOpen, Plus, Trash2, ChevronRight, Database, FileText, BookOpen, RefreshCw } from 'lucide-react'
import toast from 'react-hot-toast'
import { knowledgeApi, type KnowledgeBase } from '../api/knowledge'
import { PageHeader, Spinner, EmptyState, Button, Badge, Card } from '../components/ui'

function IndexStatusChips({ status }: { status: KnowledgeBase['index_status'] }) {
  return (
    <div className="flex flex-wrap gap-1.5 mt-2">
      <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${status.bm25.exists ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
        <Database size={10} />
        BM25 {status.bm25.exists ? `(${status.bm25.total_chunks ?? '?'}chunks)` : '未建'}
      </span>
      <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${status.vector.exists ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-500'}`}>
        <FileText size={10} />
        向量 {status.vector.exists ? '就绪' : '未建'}
      </span>
      <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${status.wiki.exists ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-500'}`}>
        <BookOpen size={10} />
        Wiki {status.wiki.exists ? `(${status.wiki.total_pages ?? 0}页)` : '未建'}
      </span>
    </div>
  )
}

function CreateModal({ onClose, onCreated }: { onClose: () => void; onCreated: () => void }) {
  const [name, setName] = useState('')
  const [rootDir, setRootDir] = useState('')
  const [desc, setDesc] = useState('')
  const mut = useMutation({
    mutationFn: () => knowledgeApi.create({ name, root_dir: rootDir, description: desc }),
    onSuccess: () => { toast.success('知识体创建成功'); onCreated() },
    onError: (e: any) => toast.error(e.message ?? '创建失败'),
  })
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
        <h3 className="text-base font-semibold mb-4">新建知识体</h3>
        <div className="space-y-3">
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">名称 *</label>
            <input value={name} onChange={e => setName(e.target.value)}
              placeholder="如：海事法规" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none" />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">根目录（绝对路径）*</label>
            <input value={rootDir} onChange={e => setRootDir(e.target.value)}
              placeholder="/data/maritime" className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none" />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">描述（可选）</label>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} rows={2}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm resize-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none" />
          </div>
        </div>
        <div className="flex justify-end gap-2 mt-5">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">取消</button>
          <button
            onClick={() => mut.mutate()}
            disabled={!name || !rootDir || mut.isPending}
            className="px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 flex items-center gap-2"
          >
            {mut.isPending && <RefreshCw size={14} className="animate-spin" />}
            创建
          </button>
        </div>
      </div>
    </div>
  )
}

export default function Knowledge() {
  const navigate = useNavigate()
  const qc = useQueryClient()
  const [showCreate, setShowCreate] = useState(false)

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['knowledge'],
    queryFn: () => knowledgeApi.list(),
  })

  const deleteMut = useMutation({
    mutationFn: (id: string) => knowledgeApi.delete(id),
    onSuccess: () => { toast.success('已删除'); qc.invalidateQueries({ queryKey: ['knowledge'] }) },
    onError: (e: any) => toast.error(e.message ?? '删除失败'),
  })

  const kbs = data?.items ?? []

  return (
    <div className="p-6">
      <PageHeader
        title="知识体管理"
        description="管理知识库文件、构建索引、编译 Wiki、在线搜索测试"
        action={
          <div className="flex gap-2">
            <Button variant="secondary" size="sm" icon={<RefreshCw size={14} />} onClick={() => refetch()}>刷新</Button>
            <Button size="sm" icon={<Plus size={14} />} onClick={() => setShowCreate(true)}>新建知识体</Button>
          </div>
        }
      />

      {isLoading && (
        <div className="flex items-center justify-center h-40"><Spinner /></div>
      )}

      {!isLoading && kbs.length === 0 && (
        <EmptyState
          icon={<FolderOpen size={40} className="text-gray-300" />}
          title="暂无知识体"
          description='点击"新建知识体"，填写名称和根目录路径即可开始'
        />
      )}

      {!isLoading && kbs.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-6">
          {kbs.map(kb => (
            <Card
              key={kb.id}
              className="cursor-pointer hover:shadow-md transition-shadow"
              onClick={() => navigate(`/knowledge/${kb.id}`)}
            >
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3 min-w-0">
                  <div className="p-2 bg-indigo-50 rounded-lg shrink-0">
                    <FolderOpen size={18} className="text-indigo-600" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-gray-900 truncate">{kb.name}</p>
                    <p className="text-xs text-gray-400 font-mono truncate">{kb.root_dir}</p>
                  </div>
                </div>
                <div className="flex items-center gap-1 shrink-0 ml-2">
                  <button
                    onClick={e => { e.stopPropagation(); if (confirm('确认删除此知识体？')) deleteMut.mutate(kb.id) }}
                    className="text-gray-300 hover:text-red-500 transition-colors p-1"
                  >
                    <Trash2 size={14} />
                  </button>
                  <ChevronRight size={14} className="text-gray-300" />
                </div>
              </div>

              {kb.description && (
                <p className="text-xs text-gray-500 mt-2 line-clamp-2">{kb.description}</p>
              )}

              <IndexStatusChips status={kb.index_status} />
            </Card>
          ))}
        </div>
      )}

      {showCreate && (
        <CreateModal
          onClose={() => setShowCreate(false)}
          onCreated={() => { setShowCreate(false); qc.invalidateQueries({ queryKey: ['knowledge'] }) }}
        />
      )}
    </div>
  )
}
