import { useEffect, useState } from "react";
import {
  scanAgentInfraStack,
  generateAgentInfraFiles,
  getDocFreshnessCache,
  getAgentHealth,
  type AgentInfraStack,
  type ContractInput,
  type FileResult,
  type CachedFreshness,
  type AgentHealthReport,
} from "../../lib/commands";

const CONFIDENCE_BADGE: Record<string, string> = {
  high: "bg-green-50 text-green-700 border-green-200",
  medium: "bg-amber-50 text-amber-700 border-amber-200",
  low: "bg-gray-50 text-gray-500 border-gray-200",
};
const CONFIDENCE_LABEL: Record<string, string> = {
  high: "确认",
  medium: "推断",
  low: "弱信号",
};

const ACTION_ICON: Record<string, string> = {
  written: "✓",
  updated: "↻",
  skipped: "○",
  failed: "✗",
};
const ACTION_COLOR: Record<string, string> = {
  written: "text-green-600",
  updated: "text-blue-600",
  skipped: "text-gray-400",
  failed: "text-red-600",
};

const HEALTH_BADGE: Record<string, string> = {
  green: "bg-green-50 text-green-700 border-green-200",
  yellow: "bg-amber-50 text-amber-700 border-amber-200",
  red: "bg-red-50 text-red-700 border-red-200",
};
const HEALTH_LABEL: Record<string, string> = {
  green: "🟢 良好",
  yellow: "🟡 有风险",
  red: "🔴 需修复",
};

export function AgentInfraPanel({
  projectPath,
  projectId,
}: {
  projectPath: string;
  projectId?: string;
}) {
  const [loading, setLoading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [stack, setStack] = useState<AgentInfraStack | null>(null);
  const [contracts, setContracts] = useState<ContractInput[]>([]);
  const [report, setReport] = useState<FileResult[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 健康诊断状态
  const [healthCache, setHealthCache] = useState<CachedFreshness | null>(null);
  const [healthReport, setHealthReport] = useState<AgentHealthReport | null>(null);
  const [diagnosing, setDiagnosing] = useState(false);
  const [copied, setCopied] = useState(false);

  // 组件挂载时读取缓存健康状态
  useEffect(() => {
    if (!projectId) return;
    getDocFreshnessCache(projectId).then((cached) => {
      if (cached) setHealthCache(cached);
    });
  }, [projectId]);

  async function handleScan() {
    setLoading(true);
    setError(null);
    setReport(null);
    try {
      const result = await scanAgentInfraStack(projectPath);
      setStack(result);
      setContracts(
        result.detected_contracts.map((c) => ({
          label: c.label,
          paths: [...c.paths],
          doc: c.doc,
        }))
      );
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }

  function removeContract(idx: number) {
    setContracts((prev) => prev.filter((_, i) => i !== idx));
  }

  async function handleGenerate() {
    // 契约为空也允许生成——产出空模板骨架（与"未检测到框架特征，可直接生成空模板"文案一致）
    setGenerating(true);
    setError(null);
    try {
      const result = await generateAgentInfraFiles(projectPath, contracts);
      setReport(result.files);
    } catch (e) {
      setError(String(e));
    } finally {
      setGenerating(false);
    }
  }

  async function handleDiagnose() {
    if (!projectId) return;
    setDiagnosing(true);
    setError(null);
    setHealthReport(null);
    try {
      const result = await getAgentHealth(projectPath, projectId);
      setHealthReport(result);
      setHealthCache({ score: result.overall, details: "[]", checked_at: result.checked_at });
    } catch (e) {
      setError(String(e));
    } finally {
      setDiagnosing(false);
    }
  }

  async function handleCopy() {
    if (!healthReport) return;
    await navigator.clipboard.writeText(healthReport.fix_prompt);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="bg-white rounded-lg border border-gray-100 p-3 space-y-2">
      {/* 标题行 */}
      <div className="flex items-center justify-between">
        <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider">
          Agent 基础设施
        </p>
        {stack && (
          <div className="flex gap-1">
            {stack.context_yaml_exists ? (
              <span className="text-[10px] text-green-600 bg-green-50 border border-green-200 px-1.5 py-0.5 rounded-full">
                yaml ✓
              </span>
            ) : (
              <span className="text-[10px] text-amber-600 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded-full">
                yaml 未生成
              </span>
            )}
            {stack.meta_rules_present && (
              <span className="text-[10px] text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full">
                元规则 ✓
              </span>
            )}
          </div>
        )}
      </div>

      <p className="text-[11px] text-gray-500 leading-relaxed">
        扫描技术栈，生成三件套：
        <code className="text-[10px] bg-gray-100 px-1 rounded">project-context.yaml</code>
        、元规则注入、
        <code className="text-[10px] bg-gray-100 px-1 rounded">doc-freshness.md</code>
      </p>

      {/* 扫描按钮 */}
      {!stack && (
        <button
          onClick={handleScan}
          disabled={loading}
          className="w-full py-1.5 rounded-lg bg-indigo-600 text-white text-xs hover:bg-indigo-700 disabled:opacity-50 transition-colors"
        >
          {loading ? "扫描中…" : "🔍 扫描技术栈"}
        </button>
      )}

      {/* 扫描结果 + 可编辑契约列表 */}
      {stack && (
        <div className="space-y-2">
          {contracts.length === 0 ? (
            <p className="text-[11px] text-gray-400 italic">
              未检测到框架特征，可直接生成空模板
            </p>
          ) : (
            <div className="space-y-1">
              <p className="text-[10px] text-gray-500 font-semibold">
                检测到 {contracts.length} 个外部契约（可移除不需要的）
              </p>
              {contracts.map((c, idx) => {
                const original = stack.detected_contracts[idx];
                const conf = original?.confidence ?? "medium";
                return (
                  <div
                    key={idx}
                    className="flex items-start gap-1.5 bg-gray-50 rounded p-1.5"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-1 flex-wrap">
                        <span className="text-[10px] font-medium text-gray-700">
                          {c.label}
                        </span>
                        <span
                          className={`text-[9px] border px-1 rounded-full ${CONFIDENCE_BADGE[conf] ?? CONFIDENCE_BADGE.medium}`}
                        >
                          {CONFIDENCE_LABEL[conf] ?? conf}
                        </span>
                      </div>
                      <p className="text-[10px] text-gray-400 font-mono mt-0.5 truncate">
                        {c.paths.join(", ")}
                      </p>
                    </div>
                    <button
                      onClick={() => removeContract(idx)}
                      className="text-gray-300 hover:text-red-400 text-xs flex-shrink-0 mt-0.5"
                      title="移除此契约"
                    >
                      ✕
                    </button>
                  </div>
                );
              })}
            </div>
          )}

          {/* 重新扫描 + 生成 */}
          <div className="flex gap-1.5 pt-0.5">
            <button
              onClick={() => { setStack(null); setContracts([]); setReport(null); }}
              className="flex-1 py-1.5 rounded-lg border border-gray-200 text-gray-500 text-xs hover:bg-gray-50 transition-colors"
            >
              重新扫描
            </button>
            <button
              onClick={handleGenerate}
              disabled={generating || !projectId}
              title={!projectId ? "需要 projectId" : undefined}
              className="flex-1 py-1.5 rounded-lg bg-indigo-600 text-white text-xs hover:bg-indigo-700 disabled:opacity-50 transition-colors"
            >
              {generating ? "生成中…" : "⚡ 生成三件套"}
            </button>
          </div>
        </div>
      )}

      {/* 生成结果 */}
      {report && (
        <div className="space-y-0.5 pt-0.5 border-t border-gray-100">
          <p className="text-[10px] text-gray-500 font-semibold">生成结果</p>
          {report.map((f) => (
            <p key={f.path} className="text-[10px] font-mono flex items-center gap-1">
              <span className={ACTION_COLOR[f.action] ?? "text-gray-500"}>
                {ACTION_ICON[f.action] ?? "?"}
              </span>
              <span className="text-gray-600 truncate flex-1">{f.path}</span>
              <span className="text-gray-400 flex-shrink-0">{f.detail}</span>
            </p>
          ))}
          <p className="text-[10px] text-amber-600 pt-0.5">
            ⚠ 生成的文件需 git commit 后才对腐化评分生效（评分基于提交时间）
          </p>
        </div>
      )}

      {/* 健康诊断区块 */}
      {projectId && (
        <div className="border-t border-gray-100 pt-2 space-y-1.5">
          <div className="flex items-center justify-between">
            <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider">
              Agent 健康诊断
            </p>
            {healthCache && (
              <span
                className={`text-[10px] border px-1.5 py-0.5 rounded-full ${HEALTH_BADGE[healthCache.score] ?? HEALTH_BADGE.green}`}
              >
                {HEALTH_LABEL[healthCache.score] ?? healthCache.score}
              </span>
            )}
          </div>

          {healthCache && !healthReport && (
            <p className="text-[10px] text-gray-400">
              上次检测：{healthCache.checked_at.slice(0, 10)}
            </p>
          )}

          <button
            onClick={handleDiagnose}
            disabled={diagnosing}
            className="w-full py-1.5 rounded-lg bg-violet-600 text-white text-xs hover:bg-violet-700 disabled:opacity-50 transition-colors"
          >
            {diagnosing ? "检测中…" : healthCache ? "🔄 重新检测 & 生成修正指令" : "🩺 生成修正指令"}
          </button>

          {/* 诊断结果 */}
          {healthReport && (
            <div className="space-y-1.5">
              <p className="text-[10px] text-gray-400">
                检测时间：{healthReport.checked_at.slice(0, 10)}
              </p>

              {healthReport.issues.length === 0 ? (
                <p className="text-[10px] text-green-600">✅ 所有检查通过</p>
              ) : (
                <div className="space-y-0.5">
                  {healthReport.issues.map((issue, idx) => (
                    <p key={idx} className="text-[10px] text-gray-600 flex gap-1 leading-relaxed">
                      <span className="flex-shrink-0">
                        {issue.level === "error" ? "❌" : "⚠️"}
                      </span>
                      <span className="min-w-0">{issue.title}</span>
                    </p>
                  ))}
                </div>
              )}

              {/* 可复制文本框 */}
              <div className="relative">
                <textarea
                  readOnly
                  value={healthReport.fix_prompt}
                  rows={6}
                  className="w-full text-[10px] font-mono bg-gray-50 border border-gray-200 rounded p-1.5 resize-none focus:outline-none"
                />
                <button
                  onClick={handleCopy}
                  className="absolute top-1 right-1 text-[9px] bg-white border border-gray-200 rounded px-1.5 py-0.5 hover:bg-gray-50 transition-colors"
                >
                  {copied ? "✓ 已复制" : "复制"}
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {error && (
        <p className="text-[11px] text-red-600 font-mono break-all">{error}</p>
      )}
    </div>
  );
}
