import { useState, useEffect, useRef } from "react";
import { generateBlueprintPrompt, syncBlueprintRules, type BlueprintStatus, type SyncResult } from "../../lib/commands";

interface Props {
  projectName: string;
  projectPath: string;
  bpStatus: BlueprintStatus["status"];
  onClose: () => void;
  onSynced?: () => void; // 同步完成后通知父组件刷新状态
}

// ── 规则同步确认模式（rules_outdated）────────────────────────────────────────

function SyncConfirmView({
  projectName, projectPath, onClose, onSynced,
}: {
  projectName: string;
  projectPath: string;
  onClose: () => void;
  onSynced?: () => void;
}) {
  const [syncing, setSyncing] = useState(false);
  const [result, setResult] = useState<SyncResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSync = async () => {
    setSyncing(true);
    setError(null);
    try {
      const res = await syncBlueprintRules(projectPath);
      setResult(res);
      onSynced?.();
    } catch (e) {
      setError(String(e));
    } finally {
      setSyncing(false);
    }
  };

  return (
    <>
      {/* 头部 */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
        <div>
          <h2 className="text-sm font-semibold text-gray-800">规则版本待更新</h2>
          <p className="text-xs text-gray-400 mt-0.5">{projectName}</p>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-lg leading-none">×</button>
      </div>

      {/* 说明 */}
      <div className="px-5 py-4 flex flex-col gap-4">
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg px-4 py-3 text-xs text-yellow-800 space-y-1.5">
          <p className="font-semibold">将执行以下操作：</p>
          <ul className="space-y-1 pl-3 list-disc">
            <li>覆盖写入 <code className="font-mono bg-yellow-100 px-1 rounded">.blueprint/CONVENTIONS.md</code>（升级至最新版本）</li>
            <li>更新 <code className="font-mono bg-yellow-100 px-1 rounded">CLAUDE.md</code> 中的蓝图规则区块</li>
          </ul>
          <p className="text-yellow-600 pt-1">不会影响项目的其他文件和蓝图内容。</p>
        </div>

        {result && (
          <div className="bg-green-50 border border-green-200 rounded-lg px-4 py-3 text-xs text-green-800">
            <p className="font-semibold mb-1">✓ 同步完成</p>
            <p className="font-mono text-green-700">{result.message}</p>
          </div>
        )}

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-xs text-red-700 font-mono break-all">
            {error}
          </div>
        )}
      </div>

      {/* 底部操作 */}
      <div className="px-5 py-3 border-t border-gray-100 flex justify-end gap-2">
        <button
          onClick={onClose}
          className="px-4 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 transition-colors"
        >
          {result ? "关闭" : "取消"}
        </button>
        {!result && (
          <button
            onClick={handleSync}
            disabled={syncing}
            className="px-4 py-1.5 rounded-lg bg-yellow-500 text-white text-sm hover:bg-yellow-600 disabled:opacity-50 transition-colors min-w-[80px]"
          >
            {syncing ? "同步中…" : "确认同步"}
          </button>
        )}
      </div>
    </>
  );
}

// ── 提示词生成模式（none / content_stale）────────────────────────────────────

function PromptView({
  projectName, projectPath, bpStatus, onClose,
}: {
  projectName: string;
  projectPath: string;
  bpStatus: "none" | "content_stale";
  onClose: () => void;
}) {
  const [prompt, setPrompt] = useState<string>("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const promptType = bpStatus === "none" ? "init" : "sync";
  const title = bpStatus === "none" ? "初始化蓝图" : "同步蓝图描绘";
  const hint = bpStatus === "none"
    ? "将以下提示词复制后粘贴给 Claude Opus，让它为项目创建蓝图"
    : "将以下提示词复制后粘贴给 Claude Opus，让它更新项目蓝图";

  useEffect(() => {
    setLoading(true);
    setError(null);
    generateBlueprintPrompt(projectPath, promptType)
      .then(setPrompt)
      .catch((e) => setError(String(e)))
      .finally(() => setLoading(false));
  }, [projectPath, promptType]);

  const handleCopy = () => {
    navigator.clipboard.writeText(prompt).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  return (
    <>
      {/* 头部 */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
        <div>
          <h2 className="text-sm font-semibold text-gray-800">{title}</h2>
          <p className="text-xs text-gray-400 mt-0.5">{projectName}</p>
        </div>
        <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-lg leading-none">×</button>
      </div>

      {/* 说明 */}
      <div className="px-5 py-3 bg-amber-50 border-b border-amber-100">
        <p className="text-xs text-amber-700">
          🤖 {hint}，由 Claude 负责理解和创作蓝图内容。
        </p>
      </div>

      {/* 提示词区域 */}
      <div className="flex-1 overflow-hidden flex flex-col px-5 py-4 gap-3">
        {loading ? (
          <div className="flex-1 flex items-center justify-center text-sm text-gray-400">
            生成提示词中…
          </div>
        ) : error ? (
          <div className="flex-1 flex items-center justify-center">
            <p className="text-sm text-red-500 font-mono break-all">{error}</p>
          </div>
        ) : (
          <textarea
            ref={textareaRef}
            readOnly
            value={prompt}
            className="flex-1 font-mono text-xs text-gray-700 bg-gray-50 border border-gray-200 rounded-lg p-3 resize-none outline-none focus:ring-2 focus:ring-blue-200"
            onClick={() => textareaRef.current?.select()}
          />
        )}
      </div>

      {/* 底部操作 */}
      <div className="px-5 py-3 border-t border-gray-100 flex items-center justify-between">
        <p className="text-xs text-gray-400">点击文本框可全选</p>
        <div className="flex gap-2">
          <button
            onClick={onClose}
            className="px-4 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 transition-colors"
          >
            关闭
          </button>
          <button
            onClick={handleCopy}
            disabled={loading || !!error}
            className="px-4 py-1.5 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50 transition-colors min-w-[80px]"
          >
            {copied ? "已复制 ✓" : "复制提示词"}
          </button>
        </div>
      </div>
    </>
  );
}

// ── 主组件 ────────────────────────────────────────────────────────────────────

export function BlueprintPromptModal({ projectName, projectPath, bpStatus, onClose, onSynced }: Props) {
  const handleBackdrop = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) onClose();
  };

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
      onClick={handleBackdrop}
    >
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-2xl flex flex-col h-[75vh]">
        {bpStatus === "rules_outdated" ? (
          <SyncConfirmView
            projectName={projectName}
            projectPath={projectPath}
            onClose={onClose}
            onSynced={onSynced}
          />
        ) : (
          <PromptView
            projectName={projectName}
            projectPath={projectPath}
            bpStatus={bpStatus as "none" | "content_stale"}
            onClose={onClose}
          />
        )}
      </div>
    </div>
  );
}
