import type { VersionInfo } from "@/api/types";
import { App } from "@capacitor/app";
import { alertController } from "@ionic/vue";
import { i18n } from "@/locales";

/**
 * 版本比较函数
 * @param version1 版本号1，如 "1.2.3"
 * @param version2 版本号2，如 "1.2.4"
 * @returns 如果 version1 < version2 返回 -1，相等返回 0，大于返回 1
 */
function compareVersion(version1: string, version2: string): number {
  const v1Parts = version1.split(".").map(Number);
  const v2Parts = version2.split(".").map(Number);
  const maxLength = Math.max(v1Parts.length, v2Parts.length);

  for (let i = 0; i < maxLength; i++) {
    const v1Part = v1Parts[i] || 0;
    const v2Part = v2Parts[i] || 0;

    if (v1Part < v2Part)
      return -1;
    if (v1Part > v2Part)
      return 1;
  }

  return 0;
}

/**
 * 应用更新检查
 */
export function useAppUpdate() {
  const state = reactive({
    isChecking: false,
    hasUpdate: false,
    latestVersion: "",
    currentVersion: "",
    forceUpdate: false,
    updateMessage: "",
    updateUrl: "",
  });
  const platform = usePlatform();

  /**
   * 获取当前应用版本
   */
  async function getCurrentVersion(): Promise<string> {
    try {
      // 在原生平台使用 Capacitor App API
      if (platform !== "browser") {
        const appInfo = await App.getInfo();
        return appInfo.version;
      }

      // Web 平台从编译时注入的全局变量获取（来自 package.json）
      return __APP_VERSION__;
    }
    catch (error) {
      console.error("获取当前版本失败:", error);
      return "0.0.1";
    }
  }

  /**
   * 检查是否有新版本
   */
  async function checkForUpdate(): Promise<{
    hasUpdate: boolean;
    currentVersion: string;
    latestVersion?: string;
    forceUpdate?: boolean;
    updateMessage?: string;
    updateUrl?: string;
  }> {
    state.isChecking = true;
    if (import.meta.env.DEV) {
      const current = await getCurrentVersion();
      // 开发环境下不检查更新
      state.currentVersion = current;
      state.hasUpdate = false;
      state.latestVersion = current;
      state.forceUpdate = false;
      state.updateMessage = "";
      state.updateUrl = "";
      state.isChecking = false;
      return {
        hasUpdate: false,
        currentVersion: current,
      };
    }
    try {
      // 1. 获取当前版本
      const current = await getCurrentVersion();
      state.currentVersion = current;

      // 2. PWA 应用检查 Service Worker 更新
      if (platform === "browser" && "serviceWorker" in navigator) {
        const registration = await navigator.serviceWorker.getRegistration();
        if (registration) {
          // 触发 Service Worker 更新检查
          await registration.update();
        }
      }

      // 3. 从 Cloudflare Function 检查最新版本
      const apiUrl = window.location.origin;
      const response = await fetch(
        `${apiUrl}/api/version?platform=${platform}&currentVersion=${current}`,
        { cache: "no-cache" }, // 不使用缓存，确保获取最新版本信息
      );

      if (!response.ok) {
        console.error("检查更新失败:", response.statusText);
        return {
          hasUpdate: false,
          currentVersion: current,
        };
      }

      const versionInfo: VersionInfo = await response.json();

      // 4. 版本比较
      const isNewVersion = compareVersion(current, versionInfo.version) < 0;

      // 更新状态
      state.latestVersion = versionInfo.version;
      state.hasUpdate = isNewVersion;
      state.forceUpdate = versionInfo.forceUpdate || false;
      state.updateMessage = versionInfo.updateMessage || "";
      state.updateUrl = versionInfo.updateUrl || "";
      // 4. 检查是否低于最低支持版本（强制更新）
      if (versionInfo.minSupportVersion) {
        const isBelowMinVersion = compareVersion(current, versionInfo.minSupportVersion) < 0;
        if (isBelowMinVersion) {
          state.forceUpdate = true;
        }
      }

      return {
        hasUpdate: isNewVersion,
        currentVersion: current,
        latestVersion: versionInfo.version,
        forceUpdate: state.forceUpdate,
        updateMessage: state.updateMessage,
        updateUrl: state.updateUrl,
      };
    }
    catch (error) {
      console.error("检查更新失败:", error);
      const current = state.currentVersion || await getCurrentVersion();
      return {
        hasUpdate: false,
        currentVersion: current,
      };
    }
    finally {
      state.isChecking = false;
    }
  }

  /**
   * 打开应用商店更新页面
   */
  async function openStoreUpdate(): Promise<void> {
    if (!state.updateUrl) {
      console.warn("没有提供更新链接");
      return;
    }

    // 在原生平台打开外部链接
    if (platform !== "browser") {
      window.open(state.updateUrl, "_system");
    }
    else {
      // Web 平台直接打开链接
      window.open(state.updateUrl, "_blank");
    }
  }

  /**
   * 显示更新提示对话框
   */
  async function showUpdateDialog(): Promise<void> {
    const alert = await alertController.create({
      header: i18n.global.t("app.update.title"),
      message: state.updateMessage || i18n.global.t("app.update.message"),
      backdropDismiss: !state.forceUpdate, // 强制更新时不允许关闭
      buttons: state.forceUpdate
        ? [
            {
              text: i18n.global.t("app.update.now"),
              role: "confirm",
              handler: () => {
                applyUpdate();
              },
            },
          ]
        : [
            {
              text: i18n.global.t("app.update.later"),
              role: "cancel",
            },
            {
              text: i18n.global.t("app.update.now"),
              role: "confirm",
              handler: () => {
                applyUpdate();
              },
            },
          ],
    });

    await alert.present();
  }

  /**
   * 应用更新（重新加载应用或打开商店）
   */
  async function applyUpdate(): Promise<void> {
    // 如果是原生应用且有更新链接，打开应用商店
    if (platform !== "browser" && state.updateUrl) {
      await openStoreUpdate();
      return;
    }

    // PWA 应用更新流程
    if (platform === "browser" && "serviceWorker" in navigator) {
      const registration = await navigator.serviceWorker.getRegistration();

      if (registration) {
        // 检查是否有等待激活的 Service Worker
        const waitingWorker = registration.waiting;
        if (waitingWorker) {
          // 通知 Service Worker 跳过等待，立即激活
          (waitingWorker as ServiceWorker).postMessage({ type: "SKIP_WAITING" });

          // 等待控制器变更后重新加载
          navigator.serviceWorker.addEventListener("controllerchange", () => {
            window.location.reload();
          }, { once: true });
          return;
        }

        // 检查是否有正在安装的 Service Worker
        if (registration.installing) {
          const installingWorker = registration.installing;
          installingWorker.addEventListener("statechange", () => {
            if (installingWorker.state === "installed" && navigator.serviceWorker.controller) {
              // 新的 Service Worker 已安装，通知它跳过等待
              (installingWorker as ServiceWorker).postMessage({ type: "SKIP_WAITING" });

              navigator.serviceWorker.addEventListener("controllerchange", () => {
                window.location.reload();
              }, { once: true });
            }
          });
          return;
        }

        // 手动触发更新检查
        try {
          await registration.update();
          // 等待一小段时间让更新完成
          await new Promise(resolve => setTimeout(resolve, 1000));

          // 如果有等待的 Service Worker，激活它
          const waitingWorker = registration.waiting;
          if (waitingWorker) {
            (waitingWorker as ServiceWorker).postMessage({ type: "SKIP_WAITING" });
            navigator.serviceWorker.addEventListener("controllerchange", () => {
              window.location.reload();
            }, { once: true });
            return;
          }
        }
        catch (error) {
          console.error("Service Worker 更新失败:", error);
        }
      }
    }

    // 如果以上都没有执行，直接重新加载页面
    window.location.reload();
  }

  /**
   * 强制刷新应用（清除缓存后重新加载）
   */
  async function forceReload(): Promise<void> {
    if ("caches" in window) {
      const cacheNames = await caches.keys();
      await Promise.all(cacheNames.map(name => caches.delete(name)));
    }
    window.location.reload();
  }

  /**
   * 自动检查更新并显示提示
   */
  async function checkAndPromptUpdate(): Promise<void> {
    const result = await checkForUpdate();

    if (result.hasUpdate) {
      await showUpdateDialog();
    }
  }

  return {
    ...toRefs(state),
    checkForUpdate,
    applyUpdate,
    forceReload,
    openStoreUpdate,
    showUpdateDialog,
    checkAndPromptUpdate,
    getCurrentVersion,
  };
}
