import { useEffect, useState } from 'react';
import { StatCard } from '../components/common/StatCard';
import { EntityTag, StatusBadge } from '../components/common/EntityTag';
import { Cpu, Clock, X, Target, Hammer, CheckCircle2, Wrench, ChevronDown, ChevronRight, FileText } from 'lucide-react';
import { getCapabilities, getTools, getKnowledge } from '../services/api';
import { cn } from '../lib/utils';

function ExpandableTool({ tool }: { tool: any }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden mb-3 shadow-sm hover:border-indigo-300 transition-colors">
      <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">
          <Wrench size={14} className="text-indigo-500" />
          {tool.name || tool.id}
        </div>
        <div className="flex items-center gap-2">
           <span className={cn("text-[10px] px-2 py-0.5 rounded-full font-bold", tool.status === '已接入' || tool.status === '正常' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500')}>
             {tool.status || '未接入'}
           </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">
          {tool.introduction || '暂无详细介绍信息...'}
        </div>
      )}
    </div>
  );
}

function CapabilityDetails({ capability, allTools, allKnow, onClose }: { capability: any, allTools: any[], allKnow: any[], onClose: () => void }) {
  if (!capability) return null;
  const currentTools = allTools.filter(t => (capability.tools || []).includes(t.id));

  const renderKnowledgeList = (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}</h4>
        <div className="space-y-2">
          {kIds.map(kid => {
            const knowObj = allKnow.find(k => k.id === kid);
            const label = knowObj ? (knowObj.task || knowObj.content?.substring(0, 40)) : kid;
            return (
              <div key={kid} className="flex items-center gap-2 text-[12px] text-slate-600 bg-white border border-slate-200 p-2.5 rounded-xl hover:border-indigo-300 transition-colors cursor-pointer">
                <FileText size={14} className="text-slate-400 min-w-4" />
                <span className="truncate">{label}</span>
              </div>
            );
          })}
        </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">
          <Cpu size={24} className="text-emerald-600"/>{capability.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={capability.tools?.length > 0 ? "Ready" : "In Progress"} />
          <span className="text-sm text-slate-500">ID: {capability.id?.substring(0,8)}...</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">描述 (Description)</h3>
          <p className="text-slate-600 text-sm leading-relaxed">{capability.description}</p>
        </div>

        <div className="bg-emerald-50/50 p-4 rounded-xl border border-emerald-100/50">
          <h3 className="font-bold text-emerald-900 mb-2 text-sm">评估标准 (Criterion)</h3>
          <p className="text-emerald-700 text-sm leading-relaxed">{capability.criterion || '暂无详细评估标准'}</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">
            <Wrench size={16} className="text-indigo-600" /> 关联执行工具 ({currentTools.length})
          </h3>
          {currentTools.length === 0 ? (
            <p className="text-xs text-slate-400">目前没有任何可用的执行工具支撑此能力。</p>
          ) : (
            <div className="space-y-2">
              {currentTools.map(t => <ExpandableTool key={t.id} tool={t} />)}
            </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">
             {renderKnowledgeList("来源关联知识 (Source Knowledge)", capability.source_knowledge, "text-violet-700")}

             {currentTools.map(t => {
               const hasKnow = (t.process_knowledge?.length || 0) + (t.case_knowledge?.length || 0) + (t.tool_knowledge?.length || 0) > 0;
               if (!hasKnow) return null;
               return (
                <div key={t.id} className="mt-5 pt-4 border-t border-slate-200 border-dashed">
                  <div className="text-[11px] font-black text-slate-400 mb-3 uppercase tracking-wider">从工具继承知识: {t.name || t.id}</div>
                  {renderKnowledgeList("工序知识 (Process)", t.process_knowledge, "text-emerald-700")}
                  {renderKnowledgeList("用例知识 (Case)", t.case_knowledge, "text-amber-700")}
                  {renderKnowledgeList("工具知识 (Tool)", t.tool_knowledge, "text-indigo-700")}
                </div>
               );
             })}

             {(!(capability.source_knowledge?.length) && currentTools.length === 0) && (
                <p className="text-xs text-slate-400 my-2">该能力及下挂工具均暂无专属沉淀知识数据。</p>
             )}
          </div>
        </div>
      </div>
    </div>
  );
}

export function Capabilities() {
  const [capabilities, setCapabilities] = useState<any[]>([]);
  const [allTools, setAllTools] = useState<any[]>([]);
  const [allKnow, setAllKnow] = useState<any[]>([]);
  const [selectedCap, setSelectedCap] = useState<any>(null);

  useEffect(() => {
    Promise.all([
      getCapabilities(1000),
      getTools(1000)
    ]).then(async ([capsRes, toolsRes]) => {
      setCapabilities(capsRes.results || []);
      setAllTools(toolsRes.results || []);
      try {
        const knowRes = await getKnowledge(1, 1000);
        setAllKnow(knowRes.results || []);
      } catch (e) {
        console.warn('knowledge API not available', e);
      }
    }).catch(err => {
      console.error(err);
    });
  }, []);

  const readyCaps = capabilities.filter(c => c.tools?.length > 0);
  const wipCaps = capabilities.filter(c => !c.tools || c.tools.length === 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={capabilities.length} 
          subtext="已定义核心能力" 
          icon={Target} 
          iconBgColor="bg-amber-50" 
          iconColor="text-amber-600" 
        />
        <StatCard 
          title="工具覆盖率" 
          value={capabilities.length > 0 ? `${Math.round((readyCaps.length / capabilities.length) * 100)}%` : "0%"} 
          subtext="已接通工具链路" 
          icon={CheckCircle2} 
          iconBgColor="bg-emerald-50" 
          iconColor="text-emerald-600" 
        />
        <StatCard 
          title="关联需求数" 
          value={new Set(capabilities.flatMap(c => c.requirements || [])).size} 
          subtext="覆盖业务场景" 
          icon={Hammer} 
          iconBgColor="bg-indigo-50" 
          iconColor="text-indigo-600" 
        />
      </div>

      <div className="flex flex-col lg:flex-row gap-6 items-stretch">
        <div className={cn("transition-all duration-300 ease-in-out", selectedCap ? "w-full lg:w-2/3" : "w-full")}>
          <div className={cn("grid gap-8", selectedCap ? "grid-cols-1" : "grid-cols-1 xl:grid-cols-2")}>
            <div>
              <h2 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                就绪能力 <span className="text-slate-400 text-sm font-normal">Ready to use</span>
              </h2>
              <div className="grid grid-cols-1 gap-4">
                {readyCaps.map(cap => (
                  <div 
                    key={cap.id} 
                    className={cn(
                      "bg-white p-5 rounded-2xl border shadow-sm hover:shadow-md transition-all cursor-pointer group",
                      selectedCap?.id === cap.id ? "border-emerald-400 ring-2 ring-emerald-50" : "border-slate-100 hover:border-emerald-200"
                    )}
                    onClick={() => setSelectedCap(cap)}
                  >
                    <div className="flex justify-between items-start mb-3">
                      <h3 className="font-bold text-slate-900 group-hover:text-emerald-700 transition-colors">{cap.name}</h3>
                      <StatusBadge status="Ready" />
                    </div>
                    <p className="text-sm text-slate-500 line-clamp-2 mb-4">{cap.description}</p>
                    <div className="flex flex-wrap gap-2">
                      <EntityTag type="tool" label="Tools" count={cap.tools?.length || 0} />
                      <EntityTag type="requirement" label="Reqs" count={cap.requirements?.length || 0} />
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div>
              <h2 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-amber-500"></span>
                研发中能力 <span className="text-slate-400 text-sm font-normal">Pending integration</span>
              </h2>
              <div className="grid grid-cols-1 gap-4">
                {wipCaps.map(cap => (
                  <div 
                    key={cap.id} 
                    className={cn(
                      "bg-white p-5 rounded-2xl border shadow-sm hover:shadow-md transition-all cursor-pointer group",
                      selectedCap?.id === cap.id ? "border-amber-400 ring-2 ring-amber-50" : "border-slate-100 hover:border-amber-200"
                    )}
                    onClick={() => setSelectedCap(cap)}
                  >
                    <div className="flex justify-between items-start mb-3">
                      <h3 className="font-bold text-slate-900 group-hover:text-amber-700 transition-colors">{cap.name}</h3>
                      <StatusBadge status="In Progress" />
                    </div>
                    <p className="text-sm text-slate-500 line-clamp-2 mb-4">{cap.description}</p>
                    <div className="flex items-center justify-between">
                      <div className="flex flex-wrap gap-2">
                        <EntityTag type="requirement" label="Reqs" count={cap.requirements?.length || 0} />
                      </div>
                      <div className="text-amber-600 flex items-center gap-1 text-xs font-bold">
                        <Clock size={14} /> Awaiting Tools
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {selectedCap && (
          <div className="w-full lg:w-1/3">
            <CapabilityDetails capability={selectedCap} allTools={allTools} allKnow={allKnow} onClose={() => setSelectedCap(null)} />
          </div>
        )}
      </div>
    </div>
  );
}
