import { useState, useEffect } from 'react';
import { Target, X, CheckCircle2, Activity, Crosshair } from 'lucide-react';
import { getRequirements, getCapabilities } from '../services/api';
import { StatCard } from '../components/common/StatCard';
import { EntityTag, StatusBadge } from '../components/common/EntityTag';
import { cn } from '../lib/utils';

function RequirementDetails({ req, onClose }: { req: any, onClose: () => void }) {
  if (!req) return null;
  return (
    <div className="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm sticky top-24">
      <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">
          <Target size={24} className="text-indigo-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 gap-2">
          <StatusBadge status={req.status} />
          <span className="text-sm text-slate-500">ID: {req.id}</span>
        </div>
        <div className="bg-white p-5 rounded-2xl border border-slate-100">
          <h3 className="font-bold text-slate-900 mb-2">描述 (Description)</h3>
          <p className="text-slate-600 text-sm leading-relaxed">{req.description}</p>
        </div>
        {req.match_result && (
          <div className="bg-slate-100 p-5 rounded-2xl">
            <h3 className="font-bold text-slate-800 mb-2">匹配结果 (Match Result)</h3>
            <p className="text-slate-600 text-sm">{req.match_result}</p>
          </div>
        )}
      </div>
    </div>
  );
}

export function Requirements() {
  const [data, setData] = useState<any[]>([]);
  const [capsTotal, setCapsTotal] = useState<number>(0);
  const [selected, setSelected] = useState<any>(null);

  useEffect(() => {
    getRequirements(1000).then(res => setData(res.results || []));
    getCapabilities(1000).then(res => setCapsTotal(res.total || res.results?.length || 0));
  }, []);

  const uniqueCapsUsed = new Set(data.flatMap(r => r.atomics || [])).size;
  const coveragePerc = capsTotal > 0 ? Math.round((uniqueCapsUsed / capsTotal) * 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-2 lg:grid-cols-4 gap-6">
        <StatCard 
          title="需求总数" 
          value={data.length} 
          subtext="活跃制作需求" 
          icon={Target} 
          iconBgColor="bg-indigo-50" 
          iconColor="text-indigo-600" 
        />
        <StatCard 
          title="满足率" 
          value={data.length > 0 ? `${Math.round((data.filter(r => r.status === '已满足').length / data.length) * 100)}%` : "0%"} 
          subtext="已闭环占比" 
          icon={CheckCircle2} 
          iconBgColor="bg-emerald-50" 
          iconColor="text-emerald-600" 
        />
        <StatCard 
          title="使用能力数" 
          value={uniqueCapsUsed} 
          subtext="被激活原子能力" 
          icon={Activity} 
          iconBgColor="bg-amber-50" 
          iconColor="text-amber-600" 
        />
        <StatCard 
          title="能力覆盖率" 
          value={`${coveragePerc}%`} 
          subtext="能力库利用率" 
          icon={Crosshair} 
          iconBgColor="bg-rose-50" 
          iconColor="text-rose-600" 
        />
      </div>

      <div className="flex flex-col lg:flex-row gap-6 items-start">
        <div className={cn("transition-all duration-300 ease-in-out", selected ? "w-full lg:w-2/3" : "w-full")}>
          <div className="bg-white rounded-3xl border border-slate-100 shadow-sm overflow-hidden text-sm">
            <table className="w-full text-left">
              <thead className="bg-slate-50/50">
                <tr>
                  <th className="px-6 py-4 font-bold text-slate-600">ID</th>
                  <th className="px-6 py-4 font-bold text-slate-600">描述</th>
                  <th className="px-6 py-4 font-bold text-slate-600">状态</th>
                  <th className="px-6 py-4 font-bold text-slate-600">关联能力</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {data.map(req => (
                  <tr key={req.id} className={cn("cursor-pointer transition-colors", selected?.id === req.id ? "bg-indigo-50/50" : "hover:bg-slate-50")} onClick={() => setSelected(req)}>
                    <td className="px-6 py-4 whitespace-nowrap text-xs text-slate-400">{req.id.substring(0,8)}...</td>
                    <td className="px-6 py-4 max-w-md truncate text-slate-700 font-medium">{req.description}</td>
                    <td className="px-6 py-4"><StatusBadge status={req.status} /></td>
                    <td className="px-6 py-4">
                      <div className="flex gap-2">
                        {req.atomics?.slice(0, 2).map((a: string) => <EntityTag key={a} type="capability" label={a} />)}
                        {req.atomics?.length > 2 && <span className="text-xs text-slate-400 self-center">+{req.atomics.length - 2}</span>}
                      </div>
                    </td>
                  </tr>
                ))}
                {data.length === 0 && (
                  <tr><td colSpan={4} className="px-6 py-12 text-center text-slate-400">暂无数据</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>

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