import { useState, useEffect } from 'react';
import { Search, FileText, Star, X, Database, ChevronDown, ChevronRight, Wrench, Cpu } from 'lucide-react';
import { getKnowledge, searchKnowledge, getTags, getTools, getCapabilities } from '../services/api';
import { EntityTag } from '../components/common/EntityTag';
import { cn } from '../lib/utils';

function ExpandableRelatedItem({ type, data }: { type: 'tool' | 'cap', data: any }) {
  const [open, setOpen] = useState(false);
  const Icon = type === 'tool' ? Wrench : Cpu;
  const iconColor = type === 'tool' ? 'text-indigo-500' : 'text-pink-500';
  const badgeBg = type === 'tool' ? 'bg-indigo-50 text-indigo-700' : 'bg-pink-50 text-pink-700';
  const badgeLabel = type === 'tool' ? '执行工具' : '原子能力';

  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm hover:border-slate-300 transition-colors mb-2">
      <div 
        className="flex justify-between items-center p-3 cursor-pointer hover:bg-slate-50 transition-colors"
        onClick={() => setOpen(!open)}
      >
        <div className="flex items-center gap-2 font-bold text-sm text-slate-800 line-clamp-1 pr-2">
          <Icon size={14} className={iconColor} />
          <span className="truncate">{data.name || data.id}</span>
        </div>
        <div className="flex items-center gap-2 shrink-0">
           <span className={cn("text-[10px] px-2 py-0.5 rounded-full font-bold", badgeBg)}>
             {badgeLabel}
           </span>
           {open ? <ChevronDown size={14} className="text-slate-400"/> : <ChevronRight size={14} className="text-slate-400"/>}
        </div>
      </div>
      {open && (
        <div className="p-4 bg-slate-50 border-t border-slate-100 text-xs text-slate-600 leading-relaxed max-h-48 overflow-y-auto whitespace-pre-wrap">
          {data.description || data.introduction || '暂无详细介绍信息...'}
        </div>
      )}
    </div>
  );
}

function KnowledgeDetails({ obj, allTools, allCaps, onClose }: { obj: any, allTools: any[], allCaps: any[], onClose: () => void }) {
  if (!obj) return null;

  const rawTools = obj.tools || [];
  const validTools = rawTools.map((tid: string) => allTools.find(t => t.id === tid) || { id: tid, name: tid });

  const rawCaps = obj.capabilities || obj.support_capability || [];
  const validCaps = rawCaps.map((cid: string) => allCaps.find(c => c.id === cid) || { id: cid, name: cid });

  return (
    <div className="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm sticky top-24 max-h-[85vh] overflow-y-auto">
      <div className="flex justify-between items-start mb-6">
        <div className="flex items-center gap-2 font-bold text-lg text-slate-900 border-b pb-2 w-full">
          <Search size={24} className="text-rose-600"/>知识详情
        </div>
        <button onClick={onClose} className="p-1 hover:bg-slate-100 rounded-lg text-slate-400 absolute right-6 top-6">
          <X size={20} />
        </button>
      </div>

      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <span className="text-sm font-mono text-slate-500 bg-slate-100 px-2 py-1 rounded">ID: {obj.id?.substring(0,8)}...</span>
          <div className="flex items-center gap-1 text-amber-500 bg-amber-50 px-2 py-1 rounded-lg">
            <Star size={14} className="fill-current" />
            <span className="font-bold text-sm">{obj.score || '0.0'}</span>
          </div>
        </div>
        
        <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
          <h3 className="text-xs font-bold text-slate-500 uppercase mb-2">任务 (Task)</h3>
          <p className="text-slate-800 text-sm font-medium">{obj.task || '无任务描述'}</p>
        </div>

        <div className="bg-rose-50/50 p-4 rounded-xl border border-rose-100/50">
          <h3 className="text-xs font-bold text-rose-800 uppercase mb-2">正文内容 (Content)</h3>
          <p className="text-rose-900 text-sm leading-relaxed whitespace-pre-wrap">{obj.content || '无内容'}</p>
        </div>

        <div className="pt-4 border-t border-slate-100 mt-4">
          <h3 className="font-bold text-slate-800 mb-4 text-sm flex items-center gap-2">
            <Cpu size={16} className="text-pink-600" /> 支撑能力与工具关联
          </h3>
          
          {(validCaps.length > 0 || validTools.length > 0) ? (
            <div className="space-y-2">
              {validCaps.map((c: any) => <ExpandableRelatedItem key={c.id} type="cap" data={c} />)}
              {validTools.map((t: any) => <ExpandableRelatedItem key={t.id} type="tool" data={t} />)}
            </div>
          ) : (
            <p className="text-xs text-slate-400">当前知识卡片未关联到具体的执行工具或能力定义。</p>
          )}

          {obj.tasks && obj.tasks.length > 0 && (
            <div className="mt-4 break-words">
               <h4 className="text-xs font-bold text-slate-500 uppercase mb-2">应用需求</h4>
               <div className="flex flex-wrap gap-2">
                 {obj.tasks.map((tk: string) => <EntityTag key={tk} type="requirement" label={tk} />)}
               </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export function Knowledge() {
  const [data, setData] = useState<any[]>([]);
  const [selected, setSelected] = useState<any>(null);

  // Filters State
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [availableTags, setAvailableTags] = useState<string[]>([]);
  const [owner, setOwner] = useState("");
  const [scopes, setScopes] = useState("");
  const [selectedStatus, setSelectedStatus] = useState<string[]>(['approved', 'checked']);
  const [isSearching, setIsSearching] = useState(false);
  const [globalStats, setGlobalStats] = useState<Record<string, number>>({});
  const [allTools, setAllTools] = useState<any[]>([]);
  const [allCaps, setAllCaps] = useState<any[]>([]);

  const loadData = async (typeOverrides?: string[]) => {
    setIsSearching(true);
    try {
      const filters: Record<string, string> = {
        types: (typeOverrides || selectedTypes).join(','),
        tags: selectedTags.join(','),
        owner: owner.trim(),
        scopes: scopes.trim(),
        status: selectedStatus.join(',')
      };

      if (searchQuery.trim()) {
        const res = await searchKnowledge(searchQuery, filters);
        setData(res.results || []);
      } else {
        const res = await getKnowledge(1, 100, filters);
        setData(res.results || []);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsSearching(false);
    }
  };

  useEffect(() => {
    loadData();
    
    // Fetch Tags
    getTags().then(res => res && res.tags && setAvailableTags(res.tags)).catch(console.error);

    const fetchAllStats = async () => {
      try {
        const res = await getKnowledge(1, 1000, {});
        const allResults = res?.results || [];
        
        const stats: Record<string, number> = { total: allResults.length };
        allResults.forEach((item: any) => {
          const itemTypes = item.types || [];
          itemTypes.forEach((t: string) => {
            stats[t] = (stats[t] || 0) + 1;
          });
        });
        setGlobalStats(stats);
      } catch (e) {
        console.error("Error fetching stats:", e);
      }
    };
    fetchAllStats();
    
    // Fetch global tools and caps for cross-referencing
    getTools(1000).then(res => setAllTools(res.results || [])).catch(console.error);
    getCapabilities(1000).then(res => setAllCaps(res.results || [])).catch(console.error);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleClear = () => {
    setSearchQuery("");
    setSelectedTypes([]);
    setSelectedTags([]);
    setOwner("");
    setScopes("");
    setSelectedStatus(['approved', 'checked']);
  };

  const toggleType = (type: string) => {
    setSelectedTypes(prev => prev.includes(type) ? prev.filter(t => t !== type) : [...prev, type]);
  };

  const toggleTag = (tag: string) => {
    setSelectedTags(prev => prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag]);
  };

  const toggleStatus = (status: string) => {
    setSelectedStatus(prev => prev.includes(status) ? prev.filter(s => s !== status) : [...prev, status]);
  };

  const handleStatCardClick = (id: string) => {
    const newTypes = id === 'ALL' ? [] : [id];
    setSelectedTypes(newTypes);
    setSearchQuery(""); // Clear search query to show all matched records naturally
    setTimeout(() => loadData(newTypes), 0);
  };

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      <div className="flex justify-between items-start">
        <div>
          <h1 className="text-2xl font-black text-slate-900">知识沉淀库 (K-Data Center)</h1>
          <p className="text-slate-500 mt-1 text-sm">高密度资产管理，支持多维分类穿透。</p>
        </div>
        <div className="flex items-center gap-2 px-4 py-2 bg-white border border-slate-100 rounded-full shadow-sm text-indigo-700 font-bold text-sm">
          <Database size={16} />
          <span>{data.length || 5} 条资产已就绪</span>
        </div>
      </div>

      <div className="flex gap-4 overflow-x-auto pb-4 custom-scrollbar">
        {[
          { label: 'ALL', id: 'ALL', count: globalStats.total || 0 },
          { label: '工序', id: 'plan', count: globalStats.plan || 0 },
          { label: '用例', id: 'usecase', count: globalStats.usecase || 0 },
          { label: '工具', id: 'tool', count: globalStats.tool || 0 },
          { label: '经验', id: 'strategy', count: (globalStats.strategy || 0) + (globalStats.exp || 0) },
          { label: '定义', id: 'definition', count: globalStats.definition || 0 },
          { label: 'USER PROFILE', id: 'user profile', count: globalStats['user profile'] || 0 }
        ].map((card) => {
          const isActive = card.id === 'ALL' ? selectedTypes.length === 0 : selectedTypes.length === 1 && selectedTypes[0] === card.id;
          return (
            <div 
              key={card.id}
              onClick={() => handleStatCardClick(card.id)}
              className={cn(
                "flex-shrink-0 w-32 p-4 rounded-2xl shadow-sm flex flex-col justify-between relative cursor-pointer outline-none transition-all duration-300 border hover:-translate-y-1 hover:shadow-md",
                isActive 
                  ? "bg-[#5143e0] text-white border-[#5143e0] ring-2 ring-[#5143e0] ring-offset-2" 
                  : "bg-white text-slate-800 border-slate-100 hover:border-[#5143e0]/30"
              )}
            >
              <div className={cn("text-[10px] uppercase font-bold mb-2", isActive ? "text-indigo-200" : "text-slate-400")}>{card.label}</div>
              <div className="text-3xl font-black">{card.count}</div>
              <div className={cn("absolute right-4 bottom-4 w-1.5 h-1.5 rounded-full opacity-80", isActive ? "bg-white" : "bg-indigo-500")}></div>
            </div>
          );
        })}
      </div>

      {/* Advanced Filter Panel */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-6 space-y-6">
        {/* Semantic Search Row */}
        <div className="flex gap-4">
          <div className="relative flex-1">
             <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
             <input 
               type="text"
               value={searchQuery}
               onChange={(e) => setSearchQuery(e.target.value)}
               onKeyDown={(e) => e.key === 'Enter' && loadData()}
               placeholder="输入任务描述进行语义搜索..."
               className="w-full pl-11 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 text-sm transition-all"
             />
          </div>
          <button 
            onClick={() => loadData()}
            disabled={isSearching}
            className="px-8 py-2.5 bg-indigo-600 text-white text-sm font-bold rounded-xl shadow-md shadow-indigo-200 hover:bg-indigo-700 hover:shadow-lg hover:-translate-y-0.5 transition-all w-28 disabled:opacity-70 disabled:hover:translate-y-0 disabled:hover:shadow-md"
          >
            {isSearching ? "搜索中..." : "搜索"}
          </button>
          <button 
            onClick={handleClear}
            className="px-8 py-2.5 bg-slate-600 text-white text-sm font-bold rounded-xl shadow-md shadow-slate-200 hover:bg-slate-700 hover:shadow-lg hover:-translate-y-0.5 transition-all w-28"
          >
            清除
          </button>
        </div>
        
        {/* Filter Details */}
        <div className="grid grid-cols-1 md:grid-cols-5 gap-6 pt-2 border-t border-slate-100/60 mt-4">
          {/* Types */}
          <div>
             <h4 className="text-xs font-bold text-slate-800 mb-3 uppercase tracking-wide">类型 (Types)</h4>
             <div className="space-y-2.5">
               {['strategy', 'tool', 'user profile', 'usecase', 'definition', 'plan'].map(t => (
                 <label key={t} className="flex items-center gap-2.5 text-sm text-slate-600 cursor-pointer group">
                   <input type="checkbox" checked={selectedTypes.includes(t)} onChange={() => toggleType(t)} className="w-4 h-4 rounded text-indigo-600 border-slate-300 focus:ring-indigo-500 cursor-pointer" />
                   <span className="capitalize group-hover:text-slate-900 transition-colors">{t}</span>
                 </label>
               ))}
             </div>
          </div>
          {/* Tags */}
          <div>
             <h4 className="text-xs font-bold text-slate-800 mb-3 uppercase tracking-wide">Tags</h4>
             <div className="space-y-2.5 max-h-[150px] overflow-y-auto custom-scrollbar pr-2">
               {availableTags.length > 0 ? availableTags.map(tag => (
                 <label key={tag} className="flex items-center gap-2.5 text-sm text-slate-600 cursor-pointer group">
                   <input type="checkbox" checked={selectedTags.includes(tag)} onChange={() => toggleTag(tag)} className="w-4 h-4 rounded text-indigo-600 border-slate-300 focus:ring-indigo-500 cursor-pointer" />
                   <span className="capitalize group-hover:text-slate-900 transition-colors line-clamp-1" title={tag}>{tag}</span>
                 </label>
               )) : (
                 <span className="text-xs text-slate-400 bg-slate-50 px-2 py-1 rounded">无可用标签</span>
               )}
             </div>
          </div>
          {/* Owner */}
          <div>
             <h4 className="text-xs font-bold text-slate-800 mb-3 uppercase tracking-wide">Owner</h4>
             <input 
               type="text" 
               value={owner} 
               onChange={(e) => setOwner(e.target.value)} 
               placeholder="输入 owner" 
               className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-all placeholder:text-slate-400" 
             />
          </div>
          {/* Scopes */}
          <div>
             <h4 className="text-xs font-bold text-slate-800 mb-3 uppercase tracking-wide">Scopes</h4>
             <input 
               type="text" 
               value={scopes} 
               onChange={(e) => setScopes(e.target.value)} 
               placeholder="输入 scope" 
               className="w-full px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition-all placeholder:text-slate-400" 
             />
          </div>
          {/* Status */}
          <div>
             <h4 className="text-xs font-bold text-slate-800 mb-3 uppercase tracking-wide">Status</h4>
             <div className="space-y-2.5">
               {['approved', 'checked', 'rejected', 'pending'].map(s => (
                 <label key={s} className="flex items-center gap-2.5 text-sm text-slate-600 cursor-pointer group">
                   <input type="checkbox" checked={selectedStatus.includes(s)} onChange={() => toggleStatus(s)} className="w-4 h-4 rounded text-indigo-600 border-slate-300 focus:ring-indigo-500 cursor-pointer" />
                   <span className="capitalize group-hover:text-slate-900 transition-colors">{s}</span>
                 </label>
               ))}
             </div>
          </div>
        </div>

        <div className="pt-2">
          <button 
            onClick={() => loadData()}
            className="px-6 py-2 bg-[#444f60] text-white text-sm font-bold rounded-lg hover:bg-[#2c3441] shadow-md shadow-slate-200 hover:-translate-y-0.5 hover:shadow-lg transition-all"
          >
            应用筛选
          </button>
        </div>
      </div>

      <div className="flex flex-col lg:flex-row gap-6 items-stretch">
        <div className={cn("transition-all duration-300 ease-in-out", selected ? "w-full lg:w-2/3" : "w-full")}>
          <div className={cn("grid gap-6", selected ? "grid-cols-1" : "grid-cols-1 md:grid-cols-2")}>
            {data.map((item, idx) => (
              <div 
                key={item.id || idx} 
                className={cn(
                  "bg-white p-5 rounded-2xl border shadow-sm transition-all cursor-pointer group flex flex-col hover:shadow-md",
                  selected?.id === item.id ? "border-rose-400 ring-2 ring-rose-50" : "border-slate-100 hover:border-rose-200"
                )}
                onClick={() => setSelected(item)}
              >
                <div className="flex items-start gap-4 mb-4">
                  <div className="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center shrink-0">
                    <FileText size={20} />
                  </div>
                  <div>
                    <h3 className="font-bold text-slate-900 line-clamp-2 group-hover:text-rose-700 transition-colors text-sm">{item.task || '（无任务描述）'}</h3>
                  </div>
                </div>
                <p className="text-xs text-slate-500 line-clamp-3 mb-4 flex-1 whitespace-pre-wrap">{item.content}</p>
                <div className="flex items-center justify-between mt-auto">
                  <div className="flex items-center gap-1 text-amber-500 font-bold text-xs">
                    <Star size={12} className="fill-current" /> {item.score || 'N/A'}
                  </div>
                  <span className="text-[10px] text-slate-400 font-mono">{item.id?.substring(0,8)}</span>
                </div>
              </div>
            ))}
            {data.length === 0 && (
              <div className="col-span-full py-12 text-center text-slate-400 bg-white border border-slate-100 rounded-3xl">暂无数据</div>
            )}
          </div>
        </div>

        {selected && (
          <div className="w-full lg:w-1/3">
            <KnowledgeDetails obj={selected} allTools={allTools} allCaps={allCaps} onClose={() => setSelected(null)} />
          </div>
        )}
      </div>
    </div>
  );
}
