import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getSpaces, createSpace, updateSpace, deleteSpace, setCurrentSpace,
  githubGetToken, githubGetAccount, gitStatus, getProjects, type Space,
} from "../../lib/commands";
import type { SpacesJson } from "../../lib/spacesSync";
import { formatRelativeTime, recordPushToRemote } from "../../lib/spacesSync";
import { useUIStore } from "../../store/ui";

interface Props {
  spacesJson: SpacesJson | null;
}

export function SpacesPage({ spacesJson }: Props) {
  const [showSpaceForm, setShowSpaceForm] = useState<Space | null | undefined>(undefined);
  const [syncing, setSyncing] = useState(false);
  const qc = useQueryClient();
  const showToast = useUIStore((s) => s.showToast);

  const { data: spaces = [], refetch: refetchSpaces } = useQuery({
    queryKey: ["spaces"],
    queryFn: getSpaces,
  });
  const currentSpace = spaces.find((s) => s.is_current);

  const { data: projects = [] } = useQuery({
    queryKey: ["projects", currentSpace?.id],
    queryFn: () => getProjects(undefined, currentSpace?.id),
    enabled: !!currentSpace,
  });

  const handleManualSync = async () => {
    if (!currentSpace) return;
    setSyncing(true);
    try {
      const token = await githubGetToken();
      const account = await githubGetAccount();
      if (!token || !account) {
        showToast("未登录 GitHub，无法同步");
        return;
      }
      const syncable = projects.filter((p) => p.repo_url && (p.win_path || p.wsl_path));
      let successCount = 0;
      for (const project of syncable) {
        const localPath = project.win_path ?? project.wsl_path!;
        try {
          const status = await gitStatus(localPath);
          await recordPushToRemote(
            token,
            account.username,
            currentSpace.id,
            currentSpace.name,
            project.repo_url!,
            status.branch,
            status.last_commit_msg
          );
          successCount++;
        } catch (e) {
          console.warn(`同步项目 ${project.name} 失败:`, e);
        }
      }
      qc.invalidateQueries({ queryKey: ["spacesSync"] });
      showToast(
        syncable.length === 0
          ? "没有可同步的项目"
          : `已同步 ${successCount}/${syncable.length} 个项目`
      );
    } catch (e) {
      showToast("同步失败");
    } finally {
      setSyncing(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto w-full px-6 py-6 pb-12 space-y-8">
      {/* 本机空间管理 */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-sm font-semibold text-gray-700">本机空间</h2>
          <div className="flex gap-2">
            <button
              onClick={handleManualSync}
              disabled={syncing || !currentSpace}
              className="px-3 py-1.5 rounded-lg text-xs border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-50"
              title="将当前空间各项目的 git 状态同步到云端（.dev-spaces）"
            >
              {syncing ? "同步中…" : "同步到云端"}
            </button>
            <button
              onClick={() => setShowSpaceForm(null)}
              className="px-3 py-1.5 rounded-lg text-xs bg-blue-600 text-white hover:bg-blue-700"
            >
              + 新建空间
            </button>
          </div>
        </div>
        <div className="space-y-2">
          {spaces.map((s) => (
            <div
              key={s.id}
              className={`flex items-center gap-3 p-4 rounded-xl border transition-colors ${
                s.is_current
                  ? "border-blue-200 bg-blue-50"
                  : "border-gray-100 bg-white hover:bg-gray-50"
              }`}
            >
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-gray-800 text-sm">{s.name}</span>
                  {s.is_current && (
                    <span className="px-1.5 py-0.5 rounded text-xs bg-blue-100 text-blue-700">当前</span>
                  )}
                </div>
              </div>
              <div className="flex gap-1.5 shrink-0">
                {!s.is_current && (
                  <button
                    onClick={async () => {
                      await setCurrentSpace(s.id);
                      refetchSpaces();
                      qc.invalidateQueries({ queryKey: ["projects"] });
                    }}
                    className="px-2.5 py-1 rounded border border-blue-200 text-xs text-blue-600 hover:bg-blue-50"
                  >
                    切换
                  </button>
                )}
                <button
                  onClick={() => setShowSpaceForm(s)}
                  className="px-2.5 py-1 rounded border border-gray-200 text-xs text-gray-600 hover:bg-white"
                >
                  编辑
                </button>
                {!s.is_current && (
                  <button
                    onClick={async () => {
                      await deleteSpace(s.id);
                      refetchSpaces();
                    }}
                    className="px-2.5 py-1 rounded border border-red-200 text-xs text-red-500 hover:bg-red-50"
                  >
                    删除
                  </button>
                )}
              </div>
            </div>
          ))}
          {spaces.length === 0 && (
            <div className="text-center py-12 text-gray-400 text-sm border border-dashed border-gray-200 rounded-xl">
              还没有空间，点击「新建空间」开始
            </div>
          )}
        </div>
      </section>

      {/* 跨端动态 */}
      {spacesJson && (
        <section>
          <h2 className="text-sm font-semibold text-gray-700 mb-4">跨端动态</h2>
          <div className="space-y-3">
            {Object.entries(spacesJson.spaces)
              .filter(([spaceId]) => !currentSpace || spaceId !== currentSpace.id)
              .map(([spaceId, spaceInfo]) => {
                const projectEntries = Object.entries(spaceInfo.projects);
                if (projectEntries.length === 0) return null;
                return (
                  <div key={spaceId} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
                    <div className="flex items-center gap-2 mb-3">
                      <span className="text-indigo-500">⇄</span>
                      <span className="font-medium text-gray-800 text-sm">{spaceInfo.name}</span>
                      <span className="text-xs text-gray-400">{projectEntries.length} 个项目有动态</span>
                    </div>
                    <div className="space-y-1.5">
                      {projectEntries
                        .sort(([, a], [, b]) => b.last_push_at.localeCompare(a.last_push_at))
                        .map(([repoUrl, info]) => {
                          const repoName = repoUrl.split("/").pop()?.replace(/\.git$/, "") ?? repoUrl;
                          return (
                            <div
                              key={repoUrl}
                              className="flex items-center gap-2 text-xs text-gray-600 py-1 border-b border-gray-50 last:border-0"
                            >
                              <span className="font-mono text-gray-500 truncate flex-1" title={repoUrl}>{repoName}</span>
                              <span className="font-mono text-indigo-500 shrink-0">{info.branch}</span>
                              {info.last_commit_msg && (
                                <span className="text-gray-400 truncate max-w-[200px]" title={info.last_commit_msg}>
                                  {info.last_commit_msg}
                                </span>
                              )}
                              <span className="text-gray-300 shrink-0">{formatRelativeTime(info.last_push_at)}</span>
                            </div>
                          );
                        })}
                    </div>
                  </div>
                );
              })}
            {Object.keys(spacesJson.spaces).filter(
              (id) => !currentSpace || id !== currentSpace.id
            ).length === 0 && (
              <div className="text-center py-8 text-gray-400 text-sm">
                暂无其他空间的动态
              </div>
            )}
          </div>
        </section>
      )}

      {showSpaceForm !== undefined && (
        <SpaceFormModal
          space={showSpaceForm}
          onClose={() => setShowSpaceForm(undefined)}
          onSaved={() => {
            setShowSpaceForm(undefined);
            refetchSpaces();
            showToast(showSpaceForm ? "已更新" : "已创建");
          }}
        />
      )}
    </div>
  );
}

function SpaceFormModal({
  space,
  onClose,
  onSaved,
}: {
  space: Space | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [name, setName] = useState(space?.name ?? "");
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      if (space) {
        await updateSpace(space.id, name.trim());
      } else {
        await createSpace(name.trim());
      }
      onSaved();
    } finally {
      setSaving(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-96 p-6 space-y-4">
        <h2 className="text-base font-semibold text-gray-800">{space ? "编辑空间" : "新建空间"}</h2>
        <div>
          <label className="block text-xs font-medium text-gray-600 mb-1">空间名称</label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="笔记本 / 日本服务器 / 公司台式机"
            className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-200"
            autoFocus
          />
        </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={handleSave}
            disabled={!name.trim() || saving}
            className="px-4 py-2 rounded-lg text-sm bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
          >
            {saving ? "保存中…" : "保存"}
          </button>
        </div>
      </div>
    </div>
  );
}
