import { useState, useEffect, useCallback } from 'react';
import type { KnowledgeBase, KnowledgeDocument, SearchChunkResult } from '@/api/knowledge';
import {
  createKB,
  listKBs,
  updateKB,
  deleteKB,
  addDocument,
  listDocuments,
  deleteDocument,
  searchKnowledge,
} from '@/api/knowledge';

interface KnowledgePanelProps {
  onClose: () => void;
}

/** 格式化时间 */
function formatTime(ts: string): string {
  try {
    const d = new Date(ts);
    return d.toLocaleString('zh-CN');
  } catch {
    return ts;
  }
}

export function KnowledgePanel({ onClose }: KnowledgePanelProps) {
  // 双标签页：知识库管理 / 搜索
  const [tab, setTab] = useState<'bases' | 'search'>('bases');

  // ========== 知识库管理状态 ==========
  const [bases, setBases] = useState<KnowledgeBase[]>([]);
  const [loadingBases, setLoadingBases] = useState(false);
  const [error, setError] = useState('');

  // 创建/编辑知识库
  const [showKBForm, setShowKBForm] = useState(false);
  const [editingKB, setEditingKB] = useState<KnowledgeBase | null>(null);
  const [kbName, setKbName] = useState('');
  const [kbDesc, setKbDesc] = useState('');
  const [savingKB, setSavingKB] = useState(false);

  // 选中知识库查看文档
  const [selectedKB, setSelectedKB] = useState<KnowledgeBase | null>(null);
  const [documents, setDocuments] = useState<KnowledgeDocument[]>([]);
  const [loadingDocs, setLoadingDocs] = useState(false);

  // 添加文档
  const [showDocForm, setShowDocForm] = useState(false);
  const [docTitle, setDocTitle] = useState('');
  const [docContent, setDocContent] = useState('');
  const [savingDoc, setSavingDoc] = useState(false);

  // ========== 搜索状态 ==========
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchChunkResult[]>([]);
  const [searchTotal, setSearchTotal] = useState(0);
  const [searching, setSearching] = useState(false);
  const [searchErr, setSearchErr] = useState('');

  // ========== 加载知识库列表 ==========
  const loadBases = useCallback(async () => {
    setLoadingBases(true);
    setError('');
    try {
      const list = await listKBs();
      setBases(list);
    } catch (e: any) {
      setError(e.message || '加载知识库失败');
    } finally {
      setLoadingBases(false);
    }
  }, []);

  useEffect(() => {
    loadBases();
  }, [loadBases]);

  // ========== 创建/更新知识库 ==========
  const handleSaveKB = async () => {
    if (!kbName.trim()) return;
    setSavingKB(true);
    setError('');
    try {
      if (editingKB) {
        await updateKB(editingKB.id, kbName.trim(), kbDesc.trim() || undefined);
      } else {
        await createKB(kbName.trim(), kbDesc.trim() || undefined);
      }
      setShowKBForm(false);
      setEditingKB(null);
      setKbName('');
      setKbDesc('');
      await loadBases();
    } catch (e: any) {
      setError(e.message || '保存知识库失败');
    } finally {
      setSavingKB(false);
    }
  };

  const handleEditKB = (kb: KnowledgeBase) => {
    setEditingKB(kb);
    setKbName(kb.name);
    setKbDesc(kb.description || '');
    setShowKBForm(true);
  };

  const handleDeleteKB = async (id: string) => {
    if (!confirm('确定要删除此知识库？所有文档将被永久删除。')) return;
    try {
      await deleteKB(id);
      if (selectedKB?.id === id) {
        setSelectedKB(null);
        setDocuments([]);
      }
      await loadBases();
    } catch (e: any) {
      setError(e.message || '删除知识库失败');
    }
  };

  // ========== 查看文档 ==========
  const handleSelectKB = async (kb: KnowledgeBase) => {
    setSelectedKB(kb);
    setLoadingDocs(true);
    try {
      const docs = await listDocuments(kb.id);
      setDocuments(docs);
    } catch (e: any) {
      setError(e.message || '加载文档失败');
    } finally {
      setLoadingDocs(false);
    }
  };

  // ========== 添加文档 ==========
  const handleAddDoc = async () => {
    if (!docTitle.trim() || !docContent.trim() || !selectedKB) return;
    setSavingDoc(true);
    setError('');
    try {
      await addDocument(selectedKB.id, docTitle.trim(), docContent.trim());
      setShowDocForm(false);
      setDocTitle('');
      setDocContent('');
      // 刷新文档列表
      const docs = await listDocuments(selectedKB.id);
      setDocuments(docs);
      // 刷新知识库列表 (更新文档计数)
      await loadBases();
    } catch (e: any) {
      setError(e.message || '添加文档失败');
    } finally {
      setSavingDoc(false);
    }
  };

  const handleDeleteDoc = async (id: string) => {
    if (!confirm('确定要删除此文档？')) return;
    try {
      await deleteDocument(id);
      if (selectedKB) {
        const docs = await listDocuments(selectedKB.id);
        setDocuments(docs);
      }
      await loadBases();
    } catch (e: any) {
      setError(e.message || '删除文档失败');
    }
  };

  // ========== 搜索 ==========
  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    setSearching(true);
    setSearchErr('');
    try {
      const res = await searchKnowledge(searchQuery.trim());
      setSearchResults(res.chunks);
      setSearchTotal(res.total);
    } catch (e: any) {
      setSearchErr(e.message || '搜索失败');
    } finally {
      setSearching(false);
    }
  };

  const handleSearchKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') handleSearch();
  };

  return (
    <div className="flex flex-col h-full">
      {/* 标签页切换 */}
      <div className="flex border-b border-gray-100 dark:border-gray-700 shrink-0">
        <button
          onClick={() => setTab('bases')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            tab === 'bases'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          📚 知识库
        </button>
        <button
          onClick={() => setTab('search')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            tab === 'search'
              ? 'text-pink-500 border-b-2 border-pink-500'
              : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
          }`}
        >
          🔍 搜索
        </button>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="mx-3 mt-2 px-3 py-2 text-xs text-red-600 bg-red-50 dark:bg-red-900/20 rounded-lg shrink-0">
          {error}
          <button className="ml-2 underline" onClick={() => setError('')}>关闭</button>
        </div>
      )}

      {/* ========== 知识库管理 ========== */}
      {tab === 'bases' && (
        <div className="flex-1 overflow-y-auto">
          {!selectedKB ? (
            /* 知识库列表 */
            <div>
              <div className="flex items-center justify-between px-3 py-2">
                <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400">
                  我的知识库
                </h3>
                <button
                  onClick={() => {
                    setEditingKB(null);
                    setKbName('');
                    setKbDesc('');
                    setShowKBForm(true);
                  }}
                  className="text-xs text-pink-500 hover:text-pink-600 transition-colors"
                >
                  + 新建
                </button>
              </div>

              {showKBForm && (
                <div className="mx-3 mb-2 p-3 bg-gray-50 dark:bg-gray-750 rounded-lg">
                  <input
                    type="text"
                    placeholder="知识库名称"
                    value={kbName}
                    onChange={(e) => setKbName(e.target.value)}
                    className="w-full px-2 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 mb-2 focus:outline-none focus:border-pink-300"
                    autoFocus
                  />
                  <textarea
                    placeholder="描述 (可选)"
                    value={kbDesc}
                    onChange={(e) => setKbDesc(e.target.value)}
                    className="w-full px-2 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 mb-2 focus:outline-none focus:border-pink-300 resize-none"
                    rows={2}
                  />
                  <div className="flex gap-2">
                    <button
                      onClick={handleSaveKB}
                      disabled={savingKB || !kbName.trim()}
                      className="px-3 py-1 text-xs bg-pink-500 text-white rounded hover:bg-pink-600 disabled:opacity-50 transition-colors"
                    >
                      {savingKB ? '保存中...' : editingKB ? '更新' : '创建'}
                    </button>
                    <button
                      onClick={() => {
                        setShowKBForm(false);
                        setEditingKB(null);
                      }}
                      className="px-3 py-1 text-xs text-gray-500 hover:text-gray-700 transition-colors"
                    >
                      取消
                    </button>
                  </div>
                </div>
              )}

              {loadingBases ? (
                <div className="px-4 py-8 text-center text-sm text-gray-400">加载中...</div>
              ) : bases.length === 0 ? (
                <div className="px-4 py-8 text-center text-sm text-gray-400">
                  📚 暂无知识库，点击「+ 新建」创建
                </div>
              ) : (
                <div className="divide-y divide-gray-100 dark:divide-gray-700">
                  {bases.map((kb) => (
                    <div
                      key={kb.id}
                      className="px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <button
                          onClick={() => handleSelectKB(kb)}
                          className="flex-1 text-left"
                        >
                          <div className="text-xs font-medium text-gray-700 dark:text-gray-300">
                            📚 {kb.name}
                          </div>
                          {kb.description && (
                            <div className="text-[10px] text-gray-400 mt-0.5 truncate">
                              {kb.description}
                            </div>
                          )}
                          <div className="text-[10px] text-gray-400 mt-0.5">
                            {kb.document_count || 0} 篇文档 · {formatTime(kb.created_at)}
                          </div>
                        </button>
                        <div className="flex gap-1 shrink-0">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleEditKB(kb);
                            }}
                            className="text-[10px] text-gray-400 hover:text-pink-500 px-1"
                            title="编辑"
                          >
                            ✏️
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeleteKB(kb.id);
                            }}
                            className="text-[10px] text-gray-400 hover:text-red-500 px-1"
                            title="删除"
                          >
                            🗑️
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : (
            /* 文档列表 */
            <div>
              <div className="flex items-center gap-2 px-3 py-2 border-b border-gray-100 dark:border-gray-700">
                <button
                  onClick={() => {
                    setSelectedKB(null);
                    setDocuments([]);
                  }}
                  className="text-xs text-gray-400 hover:text-pink-500 transition-colors"
                >
                  ← 返回
                </button>
                <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400 flex-1">
                  📚 {selectedKB.name}
                </h3>
                <button
                  onClick={() => setShowDocForm(true)}
                  className="text-xs text-pink-500 hover:text-pink-600 transition-colors"
                >
                  + 添加文档
                </button>
              </div>

              {showDocForm && (
                <div className="mx-3 my-2 p-3 bg-gray-50 dark:bg-gray-750 rounded-lg">
                  <input
                    type="text"
                    placeholder="文档标题"
                    value={docTitle}
                    onChange={(e) => setDocTitle(e.target.value)}
                    className="w-full px-2 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 mb-2 focus:outline-none focus:border-pink-300"
                    autoFocus
                  />
                  <textarea
                    placeholder="文档内容"
                    value={docContent}
                    onChange={(e) => setDocContent(e.target.value)}
                    className="w-full px-2 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 mb-2 focus:outline-none focus:border-pink-300 resize-none"
                    rows={5}
                  />
                  <div className="flex gap-2">
                    <button
                      onClick={handleAddDoc}
                      disabled={savingDoc || !docTitle.trim() || !docContent.trim()}
                      className="px-3 py-1 text-xs bg-pink-500 text-white rounded hover:bg-pink-600 disabled:opacity-50 transition-colors"
                    >
                      {savingDoc ? '保存中...' : '添加'}
                    </button>
                    <button
                      onClick={() => setShowDocForm(false)}
                      className="px-3 py-1 text-xs text-gray-500 hover:text-gray-700 transition-colors"
                    >
                      取消
                    </button>
                  </div>
                </div>
              )}

              {loadingDocs ? (
                <div className="px-4 py-8 text-center text-sm text-gray-400">加载中...</div>
              ) : documents.length === 0 ? (
                <div className="px-4 py-8 text-center text-sm text-gray-400">
                  📄 暂无文档，点击「+ 添加文档」添加
                </div>
              ) : (
                <div className="divide-y divide-gray-100 dark:divide-gray-700">
                  {documents.map((doc) => (
                    <div
                      key={doc.id}
                      className="px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1 min-w-0">
                          <div className="text-xs font-medium text-gray-700 dark:text-gray-300 truncate">
                            📄 {doc.title}
                          </div>
                          <div className="text-[10px] text-gray-400 mt-0.5">
                            {doc.source_type === 'text'
                              ? '📝 文本'
                              : doc.source_type === 'file'
                                ? '📎 文件'
                                : '🔗 URL'}{' '}
                            · {doc.chunk_count || 0} 个片段 · {formatTime(doc.created_at)}
                          </div>
                        </div>
                        <button
                          onClick={() => handleDeleteDoc(doc.id)}
                          className="text-[10px] text-gray-400 hover:text-red-500 px-1 shrink-0"
                          title="删除"
                        >
                          🗑️
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* ========== 搜索 ========== */}
      {tab === 'search' && (
        <div className="flex-1 flex flex-col overflow-hidden">
          <div className="px-3 py-2 flex gap-2 shrink-0">
            <input
              type="text"
              placeholder="搜索知识库内容..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyDown={handleSearchKeyDown}
              className="flex-1 px-2 py-1.5 text-xs border border-gray-200 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:border-pink-300"
            />
            <button
              onClick={handleSearch}
              disabled={searching || !searchQuery.trim()}
              className="px-3 py-1.5 text-xs bg-pink-500 text-white rounded hover:bg-pink-600 disabled:opacity-50 transition-colors"
            >
              {searching ? '搜索中...' : '搜索'}
            </button>
          </div>

          {searchErr && (
            <div className="mx-3 mb-2 px-3 py-2 text-xs text-red-600 bg-red-50 dark:bg-red-900/20 rounded-lg">
              {searchErr}
            </div>
          )}

          <div className="flex-1 overflow-y-auto">
            {searchResults.length === 0 && !searching && searchQuery && (
              <div className="px-4 py-8 text-center text-sm text-gray-400">
                🔍 未找到匹配结果
              </div>
            )}
            {searchResults.length === 0 && !searching && !searchQuery && (
              <div className="px-4 py-8 text-center text-sm text-gray-400">
                🔍 输入关键词搜索你的知识库
              </div>
            )}
            {searching && (
              <div className="px-4 py-8 text-center text-sm text-gray-400">搜索中...</div>
            )}
            {searchResults.length > 0 && (
              <div>
                <div className="px-3 py-1.5 text-[10px] text-gray-400">
                  共 {searchTotal} 条结果
                </div>
                <div className="divide-y divide-gray-100 dark:divide-gray-700">
                  {searchResults.map((r) => (
                    <div
                      key={r.chunk_id}
                      className="px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors"
                    >
                      <div className="text-[10px] text-pink-500 mb-0.5">
                        📚 {r.kb_name} {'>'} 📄 {r.doc_title}
                      </div>
                      {r.headline && (
                        <div className="text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                          {r.headline}
                        </div>
                      )}
                      <div className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed line-clamp-3">
                        {r.content}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
