import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getSourceVersions,
  addSourceVersion,
  setPrimaryVersion,
  deleteSourceVersion,
  updateSourceProject,
  revealSourceInExplorer,
  copySourceTo,
  type SourceProject,
  type SourceVersion,
  type SourceCategory,
  type DirEntry,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";
import { LANG_COLORS, formatRelativeTime, formatSize } from "./SourceLibraryPage";
import { ProjectFormModal } from "./ProjectFormModal";
import { open } from "@tauri-apps/plugin-dialog";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

interface Props {
  project: SourceProject;
  categories: SourceCategory[];
  onBack: () => void;
  onUpdated: () => void;
}

export function SourceProjectDetail({ project, categories, onBack, onUpdated }: Props) {
  const [activeVersionId, setActiveVersionId] = useState<string | null>(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [editingNotes, setEditingNotes] = useState(false);
  const [notesText, setNotesText] = useState(project.notes || "");
  const [deleteVersionTarget, setDeleteVersionTarget] = useState<SourceVersion | null>(null);

  const qc = useQueryClient();
  const showToast = useUIStore((s) => s.showToast);

  const { data: versions = [] } = useQuery({
    queryKey: ["source_versions", project.id],
    queryFn: () => getSourceVersions(project.id),
  });

  const activeVersion = activeVersionId
    ? versions.find((v) => v.id === activeVersionId)
    : versions.find((v) => v.is_primary) || versions[0];

  const dirTree: DirEntry[] = activeVersion?.dir_tree
    ? JSON.parse(activeVersion.dir_tree)
    : [];

  // 展示的介绍内容：优先 introduction，fallback readme
  const displayIntro = project.introduction || project.readme;

  const handleSaveNotes = async () => {
    try {
      await updateSourceProject(
        project.id,
        project.name,
        project.description,
        project.category_id,
        project.language,
        project.repo_url,
        project.introduction,
        notesText,
      );
      showToast("笔记已保存");
      setEditingNotes(false);
      onUpdated();
    } catch (e) {
      showToast(`保存失败: ${e}`);
    }
  };

  const handleSetPrimary = async (v: SourceVersion) => {
    try {
      await setPrimaryVersion(v.id, project.id);
      qc.invalidateQueries({ queryKey: ["source_versions", project.id] });
      showToast("已设为主版本");
    } catch (e) {
      showToast(`操作失败: ${e}`);
    }
  };

  const handleDeleteVersion = async () => {
    if (!deleteVersionTarget) return;
    try {
      await deleteSourceVersion(deleteVersionTarget.id);
      qc.invalidateQueries({ queryKey: ["source_versions", project.id] });
      qc.invalidateQueries({ queryKey: ["source_projects"] });
      showToast("版本已删除");
      setDeleteVersionTarget(null);
    } catch (e) {
      showToast(`删除失败: ${e}`);
    }
  };

  const handleRevealInExplorer = async (path: string) => {
    try {
      await revealSourceInExplorer(path);
    } catch (e) {
      showToast(`打开失败: ${e}`);
    }
  };

  const handleCopyTo = async (source: string) => {
    const dest = await open({ directory: true, title: "选择目标目录" });
    if (!dest) return;
    try {
      const result = await copySourceTo(source, dest as string);
      showToast(`已复制到 ${result}`);
    } catch (e) {
      showToast(`复制失败: ${e}`);
    }
  };

  return (
    <div className="h-full overflow-y-auto">
      <div className="max-w-5xl mx-auto px-6 py-6">
        {/* 返回 + Header */}
        <button
          onClick={onBack}
          className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-800 mb-4 transition-colors"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
          返回列表
        </button>

        <div className="flex items-start justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-3">
              {project.name}
              <button
                onClick={() => setShowEditModal(true)}
                className="p-1 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-600"
                title="编辑项目"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 16 16">
                  <path d="M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 000-.354l-1.086-1.086z" />
                </svg>
              </button>
            </h1>
            {project.description && (
              <p className="text-sm text-gray-600 mt-1">{project.description}</p>
            )}
            <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
              {project.language && (
                <span className="flex items-center gap-1">
                  <span
                    className="w-2.5 h-2.5 rounded-full inline-block"
                    style={{ backgroundColor: LANG_COLORS[project.language] || "#959DA5" }}
                  />
                  {project.language}
                </span>
              )}
              {project.category_name && (
                <span className="px-2 py-0.5 rounded-full border border-gray-200">{project.category_name}</span>
              )}
              {project.repo_url && (
                <a
                  href={project.repo_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-500 hover:underline flex items-center gap-1"
                >
                  <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M4.75 0h6.5C12.766 0 14 1.234 14 2.75v10.5A2.75 2.75 0 0111.25 16h-6.5A2.75 2.75 0 012 13.25V2.75A2.75 2.75 0 014.75 0zm.72 5.22a.749.749 0 011.06 0L8 6.69l1.47-1.47a.749.749 0 111.06 1.06L9.06 7.75l1.47 1.47a.749.749 0 11-1.06 1.06L8 8.81l-1.47 1.47a.749.749 0 11-1.06-1.06l1.47-1.47-1.47-1.47a.749.749 0 010-1.06z" />
                  </svg>
                  仓库
                </a>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowImportModal(true)}
              className="px-3 py-1.5 text-sm bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 font-medium"
            >
              + 导入版本
            </button>
          </div>
        </div>

        {/* 主体：左侧内容 + 右侧边栏 */}
        <div className="flex gap-6">
          {/* 左侧主区域 */}
          <div className="flex-1 min-w-0 space-y-5">
            {/* 版本切换 + 文件树 */}
            {versions.length > 0 && activeVersion && (
              <div className="border border-gray-200 rounded-lg bg-white overflow-hidden">
                {/* 版本头 */}
                <div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-b border-gray-200">
                  <div className="flex items-center gap-2">
                    <svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 16 16">
                      <path d="M2.5 7.775V2.75a.25.25 0 01.25-.25h5.025a.25.25 0 01.177.073l6.25 6.25a.25.25 0 010 .354l-5.025 5.025a.25.25 0 01-.354 0l-6.25-6.25a.25.25 0 01-.073-.177z" />
                    </svg>
                    <select
                      value={activeVersion.id}
                      onChange={(e) => setActiveVersionId(e.target.value)}
                      className="text-sm font-semibold text-gray-800 bg-transparent outline-none cursor-pointer"
                    >
                      {versions.map((v) => (
                        <option key={v.id} value={v.id}>
                          {v.is_primary ? "★ " : ""}{v.version}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="flex items-center gap-3 text-xs text-gray-500">
                    <span>{formatSize(activeVersion.file_size)}</span>
                    <span>导入于 {formatRelativeTime(activeVersion.imported_at)}</span>
                  </div>
                </div>

                {/* 文件树 */}
                <div className="divide-y divide-gray-100">
                  {dirTree.length === 0 && (
                    <div className="px-4 py-8 text-center text-sm text-gray-400">目录信息暂未生成</div>
                  )}
                  {dirTree.map((entry, i) => (
                    <div key={i} className="flex items-center px-4 py-2 text-sm hover:bg-gray-50">
                      {entry.type === "dir" ? (
                        <svg className="w-4 h-4 text-blue-500 mr-3 shrink-0" fill="currentColor" viewBox="0 0 16 16">
                          <path d="M1.75 1A1.75 1.75 0 000 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0016 13.25v-8.5A1.75 1.75 0 0014.25 3H7.5a.25.25 0 01-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75z" />
                        </svg>
                      ) : (
                        <svg className="w-4 h-4 text-gray-400 mr-3 shrink-0" fill="currentColor" viewBox="0 0 16 16">
                          <path d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06zM2 1.75C2 .784 2.784 0 3.75 0h5.086c.464 0 .909.184 1.237.513l3.414 3.414c.329.328.513.773.513 1.237v8.086A1.75 1.75 0 0112.25 15h-8.5A1.75 1.75 0 012 13.25V1.75z" />
                        </svg>
                      )}
                      <span className="flex-1 text-gray-800 font-mono text-xs">
                        {entry.name}
                      </span>
                      {entry.type === "dir" && entry.children_count != null && (
                        <span className="text-xs text-gray-400">{entry.children_count} items</span>
                      )}
                    </div>
                  ))}
                </div>

                {/* 操作按钮行 */}
                <div className="flex items-center gap-2 px-4 py-3 bg-gray-50 border-t border-gray-200">
                  <button
                    onClick={() => handleRevealInExplorer(activeVersion.file_path)}
                    className="px-3 py-1.5 text-xs border border-gray-300 rounded-md text-gray-600 hover:bg-white hover:text-gray-800 flex items-center gap-1.5 transition-colors"
                  >
                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z" />
                    </svg>
                    打开所在目录
                  </button>
                  <button
                    onClick={() => handleCopyTo(activeVersion.file_path)}
                    className="px-3 py-1.5 text-xs border border-gray-300 rounded-md text-gray-600 hover:bg-white hover:text-gray-800 flex items-center gap-1.5 transition-colors"
                  >
                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
                    </svg>
                    复制到指定路径
                  </button>
                </div>
              </div>
            )}

            {/* README / 项目介绍 */}
            {displayIntro && (
              <div className="border border-gray-200 rounded-lg bg-white overflow-hidden">
                <div className="px-4 py-3 bg-gray-50 border-b border-gray-200 flex items-center gap-2">
                  <svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M0 1.75A.75.75 0 01.75 1h4.253c1.227 0 2.317.59 3 1.501A3.744 3.744 0 0111.006 1h4.245a.75.75 0 01.75.75v10.5a.75.75 0 01-.75.75h-4.507a2.25 2.25 0 00-1.591.659l-.622.621a.75.75 0 01-1.06 0l-.622-.621A2.25 2.25 0 005.258 13H.75a.75.75 0 01-.75-.75V1.75zm7.251 10.324l.004-5.073-.002-2.253A2.25 2.25 0 005.003 2.5H1.5v9h3.757a3.75 3.75 0 011.994.574zM8.755 4.75l-.004 7.322a3.752 3.752 0 011.992-.572H14.5v-9h-3.495a2.252 2.252 0 00-2.25 2.25z" />
                  </svg>
                  <span className="text-sm font-medium text-gray-700">
                    {project.introduction ? "项目介绍" : "README.md"}
                  </span>
                </div>
                <div className="px-6 py-4 prose prose-sm prose-gray max-w-none">
                  <ReactMarkdown remarkPlugins={[remarkGfm]}>
                    {displayIntro.length > 5000 ? displayIntro.slice(0, 5000) + "\n\n..." : displayIntro}
                  </ReactMarkdown>
                </div>
              </div>
            )}

            {/* 笔记（Markdown 渲染） */}
            <div className="border border-gray-200 rounded-lg bg-white overflow-hidden">
              <div className="px-4 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <svg className="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M0 3.75C0 2.784.784 2 1.75 2h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0114.25 14H1.75A1.75 1.75 0 010 12.25v-8.5zm1.75-.25a.25.25 0 00-.25.25v8.5c0 .138.112.25.25.25h12.5a.25.25 0 00.25-.25v-8.5a.25.25 0 00-.25-.25H1.75zM3.5 6.25a.75.75 0 01.75-.75h7a.75.75 0 010 1.5h-7a.75.75 0 01-.75-.75zm.75 2.25a.75.75 0 000 1.5h4a.75.75 0 000-1.5h-4z" />
                  </svg>
                  <span className="text-sm font-medium text-gray-700">笔记</span>
                </div>
                <button
                  onClick={() => { setEditingNotes(!editingNotes); setNotesText(project.notes || ""); }}
                  className="text-xs text-blue-500 hover:underline"
                >
                  {editingNotes ? "取消" : "编辑"}
                </button>
              </div>
              {editingNotes ? (
                <div className="p-4 space-y-3">
                  <textarea
                    value={notesText}
                    onChange={(e) => setNotesText(e.target.value)}
                    rows={12}
                    className="w-full border border-gray-200 rounded-md px-3 py-2 text-sm font-mono outline-none focus:ring-2 focus:ring-emerald-200 resize-y"
                    placeholder="支持 Markdown 语法：表格、列表、代码块等..."
                  />
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-gray-400">支持 Markdown 格式</span>
                    <button
                      onClick={handleSaveNotes}
                      className="px-4 py-1.5 text-sm bg-emerald-600 text-white rounded-md hover:bg-emerald-700"
                    >
                      保存
                    </button>
                  </div>
                </div>
              ) : (
                <div className="px-6 py-4">
                  {project.notes ? (
                    <div className="prose prose-sm prose-gray max-w-none">
                      <ReactMarkdown remarkPlugins={[remarkGfm]}>{project.notes}</ReactMarkdown>
                    </div>
                  ) : (
                    <p className="text-sm text-gray-400">暂无笔记，点击「编辑」添加</p>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* 右侧边栏 */}
          <div className="w-64 shrink-0 space-y-5">
            {/* About */}
            <div className="border border-gray-200 rounded-lg bg-white p-4">
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">About</h3>
              <p className="text-sm text-gray-700 mb-3">
                {project.description || "暂无描述"}
              </p>
              {project.repo_url && (
                <a
                  href={project.repo_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1.5 text-xs text-blue-500 hover:underline mb-2"
                >
                  <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z" />
                  </svg>
                  {project.repo_url.replace(/^https?:\/\//, "").slice(0, 40)}
                </a>
              )}
              <div className="flex flex-wrap gap-1.5 mt-2">
                {project.language && (
                  <span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-gray-100 text-gray-600">
                    <span
                      className="w-2 h-2 rounded-full inline-block"
                      style={{ backgroundColor: LANG_COLORS[project.language] || "#959DA5" }}
                    />
                    {project.language}
                  </span>
                )}
                {project.category_name && (
                  <span className="px-2 py-0.5 text-xs rounded-full bg-gray-100 text-gray-600">
                    {project.category_name}
                  </span>
                )}
              </div>
            </div>

            {/* Versions */}
            <div className="border border-gray-200 rounded-lg bg-white p-4">
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">
                Versions ({versions.length})
              </h3>
              <div className="space-y-2">
                {versions.map((v) => (
                  <div
                    key={v.id}
                    className={`p-2 rounded-md cursor-pointer transition-colors group ${
                      activeVersion?.id === v.id ? "bg-emerald-50 border border-emerald-200" : "hover:bg-gray-50"
                    }`}
                    onClick={() => setActiveVersionId(v.id)}
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-800">
                        {v.is_primary && <span className="text-amber-500 mr-1">★</span>}
                        {v.version}
                      </span>
                      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        {!v.is_primary && (
                          <button
                            onClick={(e) => { e.stopPropagation(); handleSetPrimary(v); }}
                            className="p-0.5 rounded text-gray-400 hover:text-amber-500"
                            title="设为主版本"
                          >
                            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 16 16">
                              <path d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.751.751 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25z" />
                            </svg>
                          </button>
                        )}
                        <button
                          onClick={(e) => { e.stopPropagation(); setDeleteVersionTarget(v); }}
                          className="p-0.5 rounded text-gray-400 hover:text-red-500"
                          title="删除版本"
                        >
                          <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M11 1.75V3h2.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75zM4.496 6.675a.75.75 0 10-1.492.15l.66 6.6A1.75 1.75 0 005.405 15h5.19c.9 0 1.652-.681 1.741-1.576l.66-6.6a.75.75 0 10-1.492-.149l-.66 6.6a.25.25 0 01-.249.225h-5.19a.25.25 0 01-.249-.225l-.66-6.6z" />
                          </svg>
                        </button>
                      </div>
                    </div>
                    <div className="text-xs text-gray-400 mt-0.5">{formatSize(v.file_size)}</div>
                  </div>
                ))}
              </div>
              <button
                onClick={() => setShowImportModal(true)}
                className="w-full mt-3 py-1.5 text-xs text-emerald-600 border border-dashed border-emerald-300 rounded-md hover:bg-emerald-50 transition-colors"
              >
                + 导入版本
              </button>
            </div>

          </div>
        </div>
      </div>

      {/* 编辑项目弹窗 */}
      {showEditModal && (
        <ProjectFormModal
          categories={categories}
          project={project}
          onClose={() => setShowEditModal(false)}
          onSaved={() => {
            setShowEditModal(false);
            onUpdated();
          }}
        />
      )}

      {/* 导入版本弹窗 */}
      {showImportModal && (
        <ImportVersionModal
          projectId={project.id}
          projectName={project.name}
          onClose={() => setShowImportModal(false)}
          onImported={() => {
            setShowImportModal(false);
            qc.invalidateQueries({ queryKey: ["source_versions", project.id] });
            qc.invalidateQueries({ queryKey: ["source_projects"] });
            onUpdated();
          }}
        />
      )}

      {/* 删除版本确认 */}
      {deleteVersionTarget && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-80 p-6 space-y-4">
            <h2 className="text-base font-semibold text-gray-800">删除版本</h2>
            <p className="text-sm text-gray-600">
              确定删除版本「{deleteVersionTarget.version}」及其文件？
            </p>
            <div className="flex justify-end gap-3">
              <button onClick={() => setDeleteVersionTarget(null)} className="px-4 py-2 rounded-lg text-sm border border-gray-200 text-gray-600 hover:bg-gray-50">取消</button>
              <button onClick={handleDeleteVersion} className="px-4 py-2 rounded-lg text-sm bg-red-600 text-white hover:bg-red-700">删除</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── 导入版本弹窗 ─────────────────────────────────────────────────────────────

function ImportVersionModal({ projectId, projectName, onClose, onImported }: {
  projectId: string;
  projectName: string;
  onClose: () => void;
  onImported: () => void;
}) {
  const [version, setVersion] = useState("");
  const [filePath, setFilePath] = useState("");
  const [importing, setImporting] = useState(false);
  const showToast = useUIStore((s) => s.showToast);

  const handleSelectDir = async () => {
    const selected = await open({ directory: true, title: "选择源码目录" });
    if (selected) setFilePath(selected as string);
  };

  const handleSelectFile = async () => {
    const selected = await open({
      directory: false,
      multiple: false,
      title: "选择源码压缩包",
      filters: [{
        name: "压缩包",
        extensions: ["zip", "tar.gz", "tgz", "tar", "gz", "rar", "7z"],
      }],
    });
    if (selected) {
      const path = selected as string;
      setFilePath(path);
      // 从文件名自动推断版本号
      if (!version.trim()) {
        const name = path.split(/[/\\]/).pop() || "";
        // 尝试提取版本号: nocodb-0.265.1.tar.gz → 0.265.1
        const verMatch = name.match(/[-_]v?(\d+\.\d+[\d.]*)/);
        if (verMatch) setVersion(`v${verMatch[1]}`);
      }
    }
  };

  const handleImport = async () => {
    if (!version.trim() || !filePath.trim()) return;
    setImporting(true);
    try {
      await addSourceVersion(projectId, projectName, version.trim(), filePath.trim());
      showToast("版本导入成功");
      onImported();
    } catch (e) {
      showToast(`导入失败: ${e}`);
    } finally {
      setImporting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl w-[420px] p-6 space-y-4">
        <h2 className="text-base font-semibold text-gray-800">导入版本</h2>
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-1">版本号</label>
          <input
            value={version}
            onChange={(e) => setVersion(e.target.value)}
            placeholder="如 v1.9.1、main@abc1234（选文件时可自动填充）"
            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200"
            autoFocus
          />
        </div>
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-1">源码文件或目录</label>
          <div className="flex gap-2">
            <input
              value={filePath}
              onChange={(e) => setFilePath(e.target.value)}
              placeholder="选择压缩包或源码目录"
              className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-200 font-mono text-xs"
            />
            <button
              onClick={handleSelectFile}
              className="px-2.5 py-2 border border-gray-300 rounded-lg text-xs text-gray-600 hover:bg-gray-50 shrink-0"
              title="选择压缩包文件"
            >
              文件
            </button>
            <button
              onClick={handleSelectDir}
              className="px-2.5 py-2 border border-gray-300 rounded-lg text-xs text-gray-600 hover:bg-gray-50 shrink-0"
              title="选择源码目录"
            >
              目录
            </button>
          </div>
          <p className="text-xs text-gray-400 mt-1">
            支持 .zip / .tar.gz / .tgz 等压缩包（复制到托管目录保管），也支持直接引用源码目录
          </p>
        </div>
        <div className="flex justify-end gap-3 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-lg text-sm border border-gray-200 text-gray-600 hover:bg-gray-50">取消</button>
          <button
            onClick={handleImport}
            disabled={!version.trim() || !filePath.trim() || importing}
            className="px-4 py-2 rounded-lg text-sm bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50"
          >
            {importing ? "导入中..." : "导入"}
          </button>
        </div>
      </div>
    </div>
  );
}
