import { useCallback, useEffect, useMemo, useState } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { createAppVersion, deleteAppVersion, listAppVersions, updateAppVersion } from "@/features/app-config/api";
import { useAppConfigAbilities } from "@/features/app-config/permissions.js";
import { appVersionSchema } from "@/features/app-config/schema";
import { parseForm } from "@/shared/forms/validation";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const emptyData = { items: [], total: 0 };

const emptyForm = () => ({
  buildNumber: "",
  description: "",
  downloadUrl: "",
  forceUpdate: false,
  platform: "android",
  version: ""
});

export function useAppVersionsPage() {
  const { appCode } = useAppScope();
  const abilities = useAppConfigAbilities();
  const confirm = useConfirm();
  const { showToast } = useToast();
  const [keyword, setKeyword] = useState("");
  const [platform, setPlatform] = useState("");
  const [activeAction, setActiveAction] = useState("");
  const [editingItem, setEditingItem] = useState(null);
  const [form, setFormState] = useState(emptyForm);
  const [loadingAction, setLoadingAction] = useState("");

  const filters = useMemo(() => ({ keyword, platform }), [keyword, platform]);
  const queryFn = useCallback(() => listAppVersions(appCode, filters), [appCode, filters]);
  const {
    data = emptyData,
    error,
    loading,
    reload
  } = useAdminQuery(queryFn, {
    enabled: Boolean(appCode),
    errorMessage: "加载版本配置失败",
    initialData: emptyData,
    queryKey: ["app-config", "versions", appCode, filters]
  });

  useEffect(() => {
    // 安装包和强更策略必须按 App 隔离；切换 App 后清除旧版本编辑态，避免发布到错误租户。
    setActiveAction("");
    setEditingItem(null);
    setFormState(emptyForm());
  }, [appCode]);

  const setForm = (patch) => {
    setFormState((current) => ({ ...current, ...patch }));
  };

  const openCreate = () => {
    setEditingItem(null);
    setFormState(emptyForm());
    setActiveAction("create");
  };

  const openEdit = (item) => {
    setEditingItem(item);
    setFormState(formFromVersion(item));
    setActiveAction("edit");
  };

  const closeDialog = () => {
    setActiveAction("");
    setEditingItem(null);
    setFormState(emptyForm());
  };

  const resetFilters = () => {
    setKeyword("");
    setPlatform("");
  };

  const submitVersion = async (event) => {
    event.preventDefault();
    const payload = parseForm(appVersionSchema, normalizeForm(form));
    const action = editingItem ? "edit" : "create";
    setLoadingAction(action);
    try {
      if (editingItem) {
        await updateAppVersion(appCode, editingItem.id, payload);
        showToast("版本配置已更新", "success");
      } else {
        await createAppVersion(appCode, payload);
        showToast("版本配置已新增", "success");
      }
      closeDialog();
      await reload();
    } catch (err) {
      showToast(err.message || "操作失败", "error");
    } finally {
      setLoadingAction("");
    }
  };

  const removeVersion = async (item) => {
    const ok = await confirm({
      confirmText: "删除",
      message: `${platformLabel(item.platform)} ${item.version} (${item.buildNumber})`,
      title: "删除版本配置",
      tone: "danger"
    });
    if (!ok) {
      return;
    }
    setLoadingAction(`delete:${item.id}`);
    try {
      await deleteAppVersion(appCode, item.id);
      await reload();
      showToast("版本配置已删除", "success");
    } catch (err) {
      showToast(err.message || "删除失败", "error");
    } finally {
      setLoadingAction("");
    }
  };

  return {
    abilities,
    activeAction,
    closeDialog,
    data,
    editingItem,
    error,
    form,
    keyword,
    loading,
    loadingAction,
    openCreate,
    openEdit,
    platform,
    reload,
    removeVersion,
    resetFilters,
    setForm,
    setKeyword,
    setPlatform,
    submitVersion
  };
}

function normalizeForm(form) {
  return {
    ...form,
    buildNumber: form.buildNumber || 0,
    description: form.description || ""
  };
}

function formFromVersion(item) {
  return {
    buildNumber: item.buildNumber === 0 || item.buildNumber ? String(item.buildNumber) : "",
    description: item.description || "",
    downloadUrl: item.downloadUrl || "",
    forceUpdate: Boolean(item.forceUpdate),
    platform: item.platform || "android",
    version: item.version || ""
  };
}

function platformLabel(value) {
  if (value === "android") {
    return "Android";
  }
  if (value === "ios") {
    return "iOS";
  }
  return value || "-";
}
