import { useState, useEffect } from 'react';
import { StatCard } from '../components/common/StatCard';
import { Wrench, X, Globe, Zap, FileText } from 'lucide-react';
import { getTools, getKnowledge } from '../services/api';
import { EntityTag, StatusBadge } from '../components/common/EntityTag';
import { cn } from '../lib/utils';

function KnowledgeItem({ label, content }: any) {
  const [open, setOpen] = useState(false);
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm hover:border-indigo-300 transition-colors">
      <div 
        className="flex items-center gap-2 text-[12px] text-slate-700 font-bold p-2.5 cursor-pointer hover:bg-slate-50 transition-colors"
        onClick={() => setOpen(!open)}
      >
        <FileText size={14} className="text-slate-400 min-w-4" />
        <span className="truncate flex-1">{label}</span>
      </div>
      {open && (
        <div className="p-3 bg-slate-50 border-t border-slate-100 text-[11px] text-slate-600 leading-relaxed max-h-48 overflow-y-auto whitespace-pre-wrap">
          {content}
        </div>
      )}
    </div>
  );
}

function ToolDetails({ tool, allKnow, onClose }: { tool: any, allKnow: any[], onClose: () => void }) {
  if (!tool) return null;

  const renderExpandableKnowledgeList = (title: string, kIds: string[], defaultColor: string) => {
    if (!kIds || kIds.length === 0) return null;
    return (
      <div className="mb-4">
        <h4 className={`text-xs font-bold mb-2 ${defaultColor}`}>{title} ({kIds.length})</h4>
        <div className="space-y-2">
          {kIds.map((kid: string) => {
            const knowObj = allKnow.find(k => k.id === kid);
            const label = knowObj ? (knowObj.task || knowObj.content?.substring(0, 40)) : kid;
            const content = knowObj ? (knowObj.content || '暂无详细正文内容') : '未找到相关知识源文件';
            return <KnowledgeItem key={kid} label={label} content={content} />;
          })}
        </div>
      </div>
    );
  };

  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">
          <Wrench size={24} className="text-amber-600"/>{tool.name}
        </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 gap-2">
          <StatusBadge status={tool.status} />
          <span className="text-sm text-slate-500">v{tool.version || '1.0'}</span>
        </div>
        
        <div className="bg-slate-50 p-4 rounded-xl border border-slate-100">
          <h3 className="font-bold text-slate-900 mb-2 text-sm">介绍 (Introduction)</h3>
          <p className="text-slate-600 text-sm leading-relaxed">{tool.introduction}</p>
        </div>

        <div className="grid grid-cols-1 gap-4">
          <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 border-dashed overflow-hidden">
            <h4 className="text-xs font-bold text-slate-500 uppercase mb-2">Input Schema</h4>
            <pre className="text-xs overflow-x-auto text-slate-700 whitespace-pre-wrap">{JSON.stringify(tool.input, null, 2)}</pre>
          </div>
          <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 border-dashed overflow-hidden">
            <h4 className="text-xs font-bold text-slate-500 uppercase mb-2">Output Schema</h4>
            <pre className="text-xs overflow-x-auto text-slate-700 whitespace-pre-wrap">{JSON.stringify(tool.output, null, 2)}</pre>
          </div>
        </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">
            <FileText size={16} className="text-violet-600" /> 沉淀知识图谱
          </h3>
          <div className="bg-slate-50 p-4 rounded-2xl border border-slate-200">
             {renderExpandableKnowledgeList("工序知识 (Process)", tool.process_knowledge, "text-emerald-700")}
             {renderExpandableKnowledgeList("用例知识 (Case)", tool.case_knowledge, "text-amber-700")}
             {renderExpandableKnowledgeList("工具知识 (Tool)", tool.tool_knowledge, "text-indigo-700")}
             
             {(!(tool.process_knowledge?.length) && !(tool.case_knowledge?.length) && !(tool.tool_knowledge?.length)) && (
                <p className="text-xs text-slate-400 my-2">该工具暂未挂载知识点数据。</p>
             )}
          </div>
        </div>
      </div>
    </div>
  );
}

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

  useEffect(() => {
    getTools(1000).then(res => setData(res.results || []));
    getKnowledge(1, 1000).then(res => setAllKnow(res.results || [])).catch(e => console.warn(e));
  }, []);

  const activeTools = data.filter(t => t.status === '已接入' || t.status === '正常' || t.status === '已上线' || t.status === 'active');
  const toolsAvailability = data.length > 0 ? Math.round((activeTools.length / data.length) * 100) : 0;
  
  const matureTools = data.filter(t => t.case_knowledge && t.case_knowledge.length > 0);
  const toolMaturity = data.length > 0 ? Math.round((matureTools.length / data.length) * 100) : 0;

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      <div>
        <h1 className="text-2xl font-black text-slate-900 mb-1">工具资源完备性分析</h1>
        <p className="text-slate-500 text-sm">技术执行层资源分布与运行状态。</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <StatCard 
          title="工具总数" 
          value={data.length} 
          subtext="活跃工具库总计" 
          icon={Wrench} 
          iconBgColor="bg-indigo-50" 
          iconColor="text-indigo-600" 
        />
        <StatCard 
          title="工具可用率" 
          value={`${toolsAvailability}%`} 
          subtext="已接入/总数" 
          icon={Globe} 
          iconBgColor="bg-blue-50" 
          iconColor="text-blue-600" 
        />
        <StatCard 
          title="工具成熟度" 
          value={`${toolMaturity}%`} 
          subtext="案例充足占比" 
          icon={Zap} 
          iconBgColor="bg-amber-50" 
          iconColor="text-amber-600" 
        />
      </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 xl:grid-cols-2" : "grid-cols-1 md:grid-cols-2 lg:grid-cols-3")}>
            {data.map(tool => (
              <div 
                key={tool.id} 
                className={cn(
                  "bg-white p-5 rounded-2xl border transition-all cursor-pointer group flex flex-col shadow-sm hover:shadow-md",
                  selected?.id === tool.id ? "border-amber-400 ring-2 ring-amber-50" : "border-slate-100 hover:border-amber-200"
                )}
                onClick={() => setSelected(tool)}
              >
                <div className="flex justify-between items-start mb-2">
                  <h3 className="font-bold text-slate-900 group-hover:text-amber-700">{tool.name}</h3>
                  <StatusBadge status={tool.status} />
                </div>
                <p className="text-sm text-slate-500 line-clamp-2 mb-4 flex-1">{tool.introduction || '暂无介绍'}</p>
                <div className="flex flex-wrap gap-2 mt-auto">
                  {(tool.capabilities || []).slice(0, 2).map((c: string) => (
                    <EntityTag key={c} type="capability" label={c} />
                  ))}
                </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">
            <ToolDetails tool={selected} allKnow={allKnow} onClose={() => setSelected(null)} />
          </div>
        )}
      </div>
    </div>
  );
}
