import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Trash2 } from 'lucide-react'
import { aiApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label, Select } from '../../components/ui/Input'
import Modal from '../../components/ui/Modal'



/** 解析 markdown 内联格式（**bold** 和 `code`）为 TextRun 数组 */


// 通用 AI 历史记录 hook

// 通用历史记录栏组件

export function KnowledgeTab() {
  const queryClient = useQueryClient()
  const [showAdd, setShowAdd] = useState(false)
  const [newItem, setNewItem] = useState({ title: '', content: '', source: '自定义', category: '其他' })
  const [adding, setAdding] = useState(false)

  const { data: knowledgeList, isLoading } = useQuery<any[]>({
    queryKey: ['rag-knowledge'],
    queryFn: async () => {
      return await aiApi.ragList()
    },
  })

  const addMutation = useMutation({
    mutationFn: async (data: typeof newItem) => {
      return await aiApi.ragAdd(data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rag-knowledge'] })
      setShowAdd(false)
      setNewItem({ title: '', content: '', source: '自定义', category: '其他' })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => aiApi.ragRemove(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['rag-knowledge'] }),
  })

  const seedMutation = useMutation({
    mutationFn: () => aiApi.ragSeed(),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['rag-knowledge'] }),
  })

  const handleAdd = async () => {
    if (!newItem.title || !newItem.content) return
    setAdding(true)
    try {
      await addMutation.mutateAsync(newItem)
    } finally {
      setAdding(false)
    }
  }

  return (
    <div className="space-y-3">
      <div className="bg-blue-50 border border-blue-200 rounded-md p-3 text-xs text-blue-700 space-y-1">
        <div className="font-medium">📖 知识库说明</div>
        <div>· 法律法规知识库由研发方定期更新维护，确保政策时效性</div>
        <div>· 您可点击「添加知识」上传企业内部制度、操作规范等，AI 问答将同时检索法律法规和企业制度</div>
        <div>· 如发现法律内容过时，请联系研发方更新</div>
      </div>
      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-500">共 {knowledgeList?.length || 0} 条知识</span>
        <div className="flex gap-2">
          <Button variant="secondary" size="sm" onClick={() => seedMutation.mutate()} disabled={seedMutation.isPending}>
            {seedMutation.isPending ? '初始化中...' : '初始化知识库'}
          </Button>
          <Button size="sm" onClick={() => setShowAdd(true)}>
            <Plus className="w-4 h-4 mr-1" />添加知识
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-gray-400">加载中...</div>
      ) : !knowledgeList || knowledgeList.length === 0 ? (
        <Card><div className="text-center py-8 text-gray-400">知识库为空，请点击「初始化知识库」</div></Card>
      ) : (
        <div className="space-y-2">
          {knowledgeList.map((item: any) => (
            <Card key={item.id}>
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-medium">{item.title}</span>
                    <span className="px-1.5 py-0.5 rounded bg-gray-100 text-gray-500 text-xs">{item.category}</span>
                  </div>
                  <p className="text-xs text-gray-500 line-clamp-2">{item.content}</p>
                  <div className="text-xs text-gray-400 mt-1">来源：{item.source}</div>
                </div>
                <button
                  onClick={() => deleteMutation.mutate(item.id)}
                  className="text-gray-400 hover:text-danger flex-shrink-0"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </Card>
          ))}
        </div>
      )}

      {showAdd && (
        <Modal open onClose={() => setShowAdd(false)}>
          <div className="space-y-3">
            <h3 className="font-medium">添加知识条目</h3>
            <div>
              <Label>标题</Label>
              <Input value={newItem.title} onChange={(e) => setNewItem({ ...newItem, title: e.target.value })} placeholder="如：劳动合同法第十条" />
            </div>
            <div>
              <Label>内容</Label>
              <textarea
                value={newItem.content}
                onChange={(e) => setNewItem({ ...newItem, content: e.target.value })}
                placeholder="法律条文或知识内容"
                rows={5}
                className="w-full px-3 py-2 rounded-md border border-gray-300 text-sm"
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>来源</Label>
                <Input value={newItem.source} onChange={(e) => setNewItem({ ...newItem, source: e.target.value })} placeholder="如：劳动合同法" />
              </div>
              <div>
                <Label>分类</Label>
                <Select value={newItem.category} onChange={(e) => setNewItem({ ...newItem, category: e.target.value })}>
                  <option value="其他">其他</option>
                  <option value="法律法规">法律法规</option>
                  <option value="司法解释">司法解释</option>
                  <option value="地方性法规">地方性法规</option>
                  <option value="案例分析">案例分析</option>
                </Select>
              </div>
            </div>
            <div className="flex gap-2 justify-end">
              <Button variant="secondary" size="sm" onClick={() => setShowAdd(false)}>取消</Button>
              <Button size="sm" onClick={handleAdd} disabled={!newItem.title || !newItem.content || adding}>
                {adding ? '添加中...' : '添加'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
