import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { open } from "@tauri-apps/plugin-dialog";
import { createProject, gitClone } from "../../lib/commands";
import { useUIStore } from "../../store/ui";
import type { SpaceCatalogItem } from "../../lib/spacesSync";

export interface DiscoverableItem extends SpaceCatalogItem {
  spaceId: string;
  spaceName: string;
}

interface Props {
  items: DiscoverableItem[];
  currentSpaceId: string;
}

/* ── 内联克隆表单 ─────────────────────────────────────────── */
function CloneForm({
  item,
  spaceId,
  onDone,
}: {
  item: DiscoverableItem;
  spaceId: string;
  onDone: () => void;
}) {
  const showToast = useUIStore((s) => s.showToast);
  // 从 repo_url 提取仓库名作为默认 id 和文件夹名
  const repoName = item.repo_url.split("/").pop()?.replace(/\.git$/, "") ?? item.name;

  const [wsId, setWsId] = useState(repoName);
  const [parentDir, setParentDir] = useState("");
  const [platform, setPlatform] = useState<"windows" | "wsl">(
    (item.platform as "windows" | "wsl") ?? "windows"
  );
  const [cloning, setCloning] = useState(false);

  // Windows 侧路径 = 父目录 + \ + 仓库名
  const winPath = parentDir ? `${parentDir}\\${repoName}` : "";

  const pickParentDir = async () => {
    const selected = await open({ directory: true, multiple: false });
    if (selected) setParentDir(selected as string);
  };

  const handleClone = async () => {
    if (!wsId.trim()) { showToast("❌ 项目 ID 不能为空"); return; }
    if (platform === "windows" && !parentDir) {
      showToast("❌ 请先选择本地目录"); return;
    }

    setCloning(true);
    try {
      if (platform === "windows") {
        await gitClone(item.repo_url, winPath);
      }
      // WSL 模式下用户需要手动克隆，这里只注册项目
      await createProject({
        id: wsId.trim(),
        name: item.name,
        description: item.description,
        tech_stack: item.tech_stack,
        repo_url: item.repo_url,
        default_branch: item.default_branch ?? "main",
        platform,
        space_id: spaceId,
        win_path: platform === "windows" ? winPath : undefined,
      });
      showToast(`✓ 已${platform === "windows" ? "克隆并" : ""}添加项目「${item.name}」`);
      onDone();
    } catch (e) {
      showToast(`❌ ${e}`);
    } finally {
      setCloning(false);
    }
  };

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

  return (
    <div className="border-t border-indigo-100 px-4 py-4 space-y-3 bg-indigo-50/40">
      {/* 平台 */}
      <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-indigo-400 bg-indigo-50 text-indigo-700 font-medium"
                : "border-gray-200 text-gray-500 hover:bg-gray-50"
            }`}
          >
            {p === "windows" ? "Windows" : "WSL / Linux"}
          </button>
        ))}
      </div>

      {/* 项目 ID */}
      <div>
        <label className="block text-xs font-medium text-gray-500 mb-1">
          项目 ID（本空间内唯一）
        </label>
        <input
          className={`${inputCls} font-mono`}
          value={wsId}
          onChange={(e) => setWsId(e.target.value)}
          placeholder={repoName}
        />
      </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
              type="button"
              onClick={pickParentDir}
              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>git clone</code>
            </p>
          )}
        </div>
      ) : (
        <div className="text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
          WSL 模式：请先在 WSL 终端中手动 <code>git clone {item.repo_url}</code>，
          添加后再在项目卡片上补充路径。
        </div>
      )}

      {/* 操作 */}
      <div className="flex justify-end gap-2 pt-1">
        <button
          onClick={handleClone}
          disabled={cloning || (platform === "windows" && !parentDir)}
          className="px-4 py-2 rounded-lg text-xs bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50 transition-colors"
        >
          {cloning
            ? "克隆中…"
            : platform === "windows"
            ? "克隆到本地"
            : "仅添加记录"}
        </button>
      </div>
    </div>
  );
}

/* ── 发现面板主体 ──────────────────────────────────────────── */
export function DiscoveryPanel({ items, currentSpaceId }: Props) {
  const qc = useQueryClient();
  const [expandedUrl, setExpandedUrl] = useState<string | null>(null);

  if (items.length === 0) return null;

  const handleCloned = () => {
    setExpandedUrl(null);
    qc.invalidateQueries({ queryKey: ["projects"] });
  };

  return (
    <section className="rounded-xl border border-indigo-200 bg-indigo-50 shadow-sm overflow-hidden">
      {/* 标题栏 */}
      <div className="flex items-center gap-2 px-5 py-3 border-b border-indigo-100">
        <span className="text-indigo-500">⬇</span>
        <h2 className="text-sm font-semibold text-indigo-800">可从其他空间接续的项目</h2>
        <span className="ml-auto text-xs text-indigo-400">{items.length} 个</span>
      </div>

      {/* 条目列表 */}
      <div className="p-4 space-y-2">
        {items.map((item) => {
          const key = item.repo_url;
          const expanded = expandedUrl === key;
          return (
            <div
              key={key}
              className="rounded-lg border border-indigo-100 bg-white overflow-hidden"
            >
              {/* 条目行 */}
              <div className="flex items-center gap-3 px-4 py-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="text-sm font-medium text-gray-800">{item.name}</span>
                    {item.tech_stack && (
                      <span className="text-xs text-gray-400">{item.tech_stack}</span>
                    )}
                    {item.default_branch && (
                      <span className="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-500 font-mono">
                        {item.default_branch}
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-1.5 mt-0.5">
                    <span className="text-xs text-indigo-400">
                      来自 <span className="font-medium text-indigo-600">{item.spaceName}</span>
                    </span>
                    <span className="text-gray-300">·</span>
                    <span className="text-xs font-mono text-gray-400 truncate max-w-xs" title={item.repo_url}>
                      {item.repo_url}
                    </span>
                  </div>
                  {item.description && (
                    <p className="text-xs text-gray-400 mt-0.5">{item.description}</p>
                  )}
                </div>
                <button
                  onClick={() => setExpandedUrl(expanded ? null : key)}
                  className={`px-3 py-1.5 rounded-lg text-xs border shrink-0 transition-colors ${
                    expanded
                      ? "border-gray-200 text-gray-500 hover:bg-gray-50"
                      : "bg-indigo-600 text-white hover:bg-indigo-700 border-transparent"
                  }`}
                >
                  {expanded ? "收起" : "接续开发"}
                </button>
              </div>

              {/* 克隆表单 */}
              {expanded && (
                <CloneForm
                  item={item}
                  spaceId={currentSpaceId}
                  onDone={handleCloned}
                />
              )}
            </div>
          );
        })}
      </div>
    </section>
  );
}
