import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { open as openDialog } from "@tauri-apps/plugin-dialog";
import {
  getGitRepos,
  mountRepo,
  gitClone,
  getProjects,
  type GitRepo,
} from "../../lib/commands";
import { useUIStore } from "../../store/ui";

interface Props {
  spaceId: string;
  onClose: () => void;
}

export function MountRepoModal({ spaceId, onClose }: Props) {
  const showToast = useUIStore((s) => s.showToast);
  const qc = useQueryClient();

  const [selected, setSelected] = useState<GitRepo | null>(null);
  const [platform, setPlatform] = useState<"windows" | "wsl">("windows");
  const [parentDir, setParentDir] = useState("");
  const [mounting, setMounting] = useState(false);
  const [search, setSearch] = useState("");

  // 所有已注册仓库
  const { data: repos = [], isLoading } = useQuery({
    queryKey: ["git-repos"],
    queryFn: getGitRepos,
  });

  // 当前空间已挂载的项目（用来过滤掉已挂载的）
  const { data: projects = [] } = useQuery({
    queryKey: ["projects", spaceId],
    queryFn: () => getProjects(undefined, spaceId),
  });

  // 当前空间已有的 repo_id 集合
  const mountedRepoIds = new Set(
    projects.map((p) => p.repo_id).filter((id): id is string => !!id)
  );

  const filtered = repos.filter(
    (r) =>
      (r.name.toLowerCase().includes(search.toLowerCase()) ||
        r.repo_url.toLowerCase().includes(search.toLowerCase()))
  );

  const repoName = selected
    ? selected.repo_url.split("/").pop()?.replace(/\.git$/, "") ?? selected.name
    : "";
  const winPath = parentDir && repoName ? `${parentDir}\\${repoName}` : "";

  const pickDir = async () => {
    const dir = await openDialog({ directory: true, title: "选择本地存放目录" });
    if (dir) setParentDir(dir as string);
  };

  const handleMount = async () => {
    if (!selected) return;
    if (platform === "windows" && !parentDir) {
      showToast("❌ 请选择本地目录");
      return;
    }
    setMounting(true);
    try {
      if (platform === "windows") {
        await gitClone(selected.repo_url, winPath);
      }
      await mountRepo({
        workspace_id: crypto.randomUUID(),
        repo_id: selected.id,
        space_id: spaceId,
        win_path: platform === "windows" ? winPath : undefined,
        platform,
      });
      qc.invalidateQueries({ queryKey: ["projects"] });
      showToast(`已${platform === "windows" ? "克隆并" : ""}挂载「${selected.name}」✓`);
      onClose();
    } catch (e) {
      showToast(`❌ ${e}`);
    } finally {
      setMounting(false);
    }
  };

  const inputCls = "w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-200";

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-2xl w-[580px] max-h-[80vh] flex flex-col border border-gray-200">
        {/* 标题 */}
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
          <h2 className="text-base font-semibold text-gray-800">从仓库导入项目</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">×</button>
        </div>

        {/* 搜索 */}
        <div className="px-4 py-3 border-b border-gray-100">
          <input
            type="text"
            placeholder="搜索已注册仓库…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className={inputCls}
          />
        </div>

        {/* 仓库列表 */}
        {isLoading ? (
          <div className="flex-1 flex items-center justify-center text-gray-400 text-sm">加载中…</div>
        ) : repos.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center text-gray-400 py-12 gap-2">
            <p className="text-2xl">📦</p>
            <p className="text-sm">还没有注册仓库</p>
            <p className="text-xs text-gray-300">请先在「仓库管理」中注册仓库</p>
          </div>
        ) : (
          <div className="flex-1 overflow-y-auto min-h-0">
            {filtered.map((repo) => {
              const alreadyMounted = mountedRepoIds.has(repo.id);
              const isSelected = selected?.id === repo.id;
              return (
                <button
                  key={repo.id}
                  onClick={() => !alreadyMounted && setSelected(isSelected ? null : repo)}
                  disabled={alreadyMounted}
                  className={`w-full text-left px-4 py-3 border-b border-gray-100 transition-colors ${
                    alreadyMounted
                      ? "opacity-40 cursor-not-allowed"
                      : isSelected
                      ? "bg-blue-50 border-l-2 border-l-blue-500"
                      : "hover:bg-gray-50"
                  }`}
                >
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="text-sm font-medium text-gray-800">{repo.name}</span>
                    {repo.tech_stack && <span className="text-xs text-gray-400">{repo.tech_stack}</span>}
                    {repo.default_branch && (
                      <span className="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-500 font-mono">{repo.default_branch}</span>
                    )}
                    {alreadyMounted && (
                      <span className="text-xs px-1.5 py-0.5 bg-green-100 text-green-600 rounded ml-auto">已挂载</span>
                    )}
                  </div>
                  <p className="text-xs text-gray-400 truncate mt-0.5 font-mono">{repo.repo_url}</p>
                  {repo.description && (
                    <p className="text-xs text-gray-300 mt-0.5 truncate">{repo.description}</p>
                  )}
                </button>
              );
            })}
            {filtered.length === 0 && (
              <div className="text-center text-gray-400 text-sm py-8">没有匹配的仓库</div>
            )}
          </div>
        )}

        {/* 选中后的配置区 */}
        {selected && (
          <div className="border-t border-gray-100 px-4 py-4 space-y-3">
            <p className="text-xs font-medium text-gray-500">
              已选择：<span className="text-gray-800 font-semibold">{selected.name}</span>
            </p>

            {/* 平台 */}
            <div className="flex gap-2">
              {(["windows", "wsl"] as const).map((p) => (
                <button
                  key={p}
                  type="button"
                  onClick={() => setPlatform(p)}
                  className={`px-3 py-1.5 rounded-lg text-xs border transition-colors ${
                    platform === p
                      ? "border-blue-400 bg-blue-50 text-blue-700 font-medium"
                      : "border-gray-200 text-gray-500 hover:bg-gray-50"
                  }`}
                >
                  {p === "windows" ? "Windows" : "WSL / Linux"}
                </button>
              ))}
            </div>

            {/* 路径 */}
            {platform === "windows" ? (
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">克隆到目录</label>
                <div className="flex gap-2">
                  <input
                    className={`${inputCls} font-mono flex-1`}
                    value={winPath}
                    readOnly
                    placeholder="请先选择父目录"
                  />
                  <button
                    onClick={pickDir}
                    className="px-3 py-2 rounded-lg border border-gray-200 text-xs text-gray-600 hover:bg-gray-50 shrink-0"
                  >
                    选择目录
                  </button>
                </div>
                {parentDir && (
                  <p className="text-xs text-gray-400 mt-1">
                    将克隆到：<code className="font-mono">{winPath}</code>
                  </p>
                )}
              </div>
            ) : (
              <p className="text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                WSL 模式：请先在 WSL 终端中手动执行{" "}
                <code className="font-mono">git clone {selected.repo_url}</code>，
                挂载后可在项目卡片上补充路径。
              </p>
            )}

            {/* 操作按钮 */}
            <div className="flex justify-end gap-2 pt-1">
              <button
                onClick={onClose}
                className="px-4 py-2 text-sm border border-gray-200 rounded-lg text-gray-600 hover:bg-gray-50"
              >
                取消
              </button>
              <button
                onClick={handleMount}
                disabled={mounting || (platform === "windows" && !parentDir)}
                className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
              >
                {mounting
                  ? "处理中…"
                  : platform === "windows"
                  ? "克隆并挂载"
                  : "挂载到此空间"}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
