import { useCallback, useEffect, useState } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { getSelectedAppCode } from "@/shared/api/request";
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";
import { createH5Link, deleteH5Link, listH5Links, updateH5Link } from "@/features/app-config/api";
import { useAppConfigAbilities } from "@/features/app-config/permissions.js";
import { h5LinkUpdateSchema } from "@/features/app-config/schema";

const emptyData = { items: [], total: 0 };
const emptyForm = () => ({ key: "", label: "", url: "" });

export function useH5ConfigPage() {
  const { appCode } = useAppScope();
  const abilities = useAppConfigAbilities();
  const confirm = useConfirm();
  const { showToast } = useToast();
  const [activeAction, setActiveAction] = useState("");
  const [actionAppCode, setActionAppCode] = useState("");
  const [editingItem, setEditingItem] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [loadingAction, setLoadingAction] = useState("");
  const queryFn = useCallback(() => listH5Links(appCode), [appCode]);
  const { data = emptyData, error, loading, reload } = useAdminQuery(queryFn, {
    enabled: Boolean(appCode),
    errorMessage: "加载 H5 配置失败",
    initialData: emptyData,
    queryKey: ["app-config", "h5-links", appCode]
  });

  const openCreate = () => {
    setEditingItem(null);
    setForm(emptyForm());
    setActionAppCode(appCode);
    setActiveAction("create");
  };

  const openEdit = (item) => {
    const itemAppCode = normalizeAppCode(item.appCode) || appCode;
    setEditingItem(item);
    setForm({ key: item.key || "", label: item.label || "", url: item.url || "" });
    // 响应中的 appCode 是该行数据的归属凭证；若页面正在切换，effect 会发现它与当前 scope 不一致并关闭弹窗。
    setActionAppCode(itemAppCode);
    setActiveAction("edit");
  };

  const closeEdit = useCallback(() => {
    setActiveAction("");
    setActionAppCode("");
    setEditingItem(null);
    setForm(emptyForm());
  }, []);

  useEffect(() => {
    if (!activeAction || sameAppCode(actionAppCode, appCode)) {
      return;
    }
    // 弹窗内容来自旧 App；切换后必须丢弃，不能让同名 key 被保存到新 App。
    closeEdit();
  }, [activeAction, actionAppCode, appCode, closeEdit]);

  const submitEdit = async (event) => {
    event.preventDefault();
    if (!isCurrentActionScope(actionAppCode, appCode)) {
      closeEdit();
      showToast("应用已切换，请重新操作", "warning");
      return;
    }
    if (!editingItem) {
      const payload = parseForm(h5LinkUpdateSchema, form);
      setLoadingAction("create");
      try {
        await createH5Link(actionAppCode, payload);
        closeEdit();
        await reload();
        showToast("H5配置已新增", "success");
      } catch (err) {
        showToast(err.message || "操作失败", "error");
      } finally {
        setLoadingAction("");
      }
      return;
    }
    const payload = parseForm(h5LinkUpdateSchema, { ...form, key: editingItem.key });
    setLoadingAction("edit");
    try {
      await updateH5Link(actionAppCode, editingItem.key, payload);
      closeEdit();
      await reload();
      showToast("H5配置已更新", "success");
    } catch (err) {
      showToast(err.message || "操作失败", "error");
    } finally {
      setLoadingAction("");
    }
  };

  const removeH5Link = async (item) => {
    const targetAppCode = normalizeAppCode(item.appCode) || appCode;
    const ok = await confirm({
      confirmText: "删除",
      message: item.label || item.key,
      title: "删除H5配置",
      tone: "danger"
    });
    if (!ok) {
      return;
    }
    if (!isCurrentActionScope(targetAppCode, appCode)) {
      showToast("应用已切换，请重新操作", "warning");
      return;
    }
    setLoadingAction(`delete:${item.key}`);
    try {
      await deleteH5Link(targetAppCode, item.key);
      await reload();
      showToast("H5配置已删除", "success");
    } catch (err) {
      showToast(err.message || "删除失败", "error");
    } finally {
      setLoadingAction("");
    }
  };

  return {
    activeAction,
    abilities,
    closeEdit,
    data,
    editingItem,
    error,
    form,
    loading,
    loadingAction,
    openCreate,
    openEdit,
    reload,
    removeH5Link,
    setForm,
    submitEdit
  };
}

function isCurrentActionScope(actionAppCode, appCode) {
  // Header 的全局值在 AppScope state 提交前已更新，双重校验能挡住切换瞬间点击提交的竞态。
  return Boolean(normalizeAppCode(actionAppCode))
    && sameAppCode(actionAppCode, appCode)
    && sameAppCode(actionAppCode, getSelectedAppCode());
}

function sameAppCode(left, right) {
  return normalizeAppCode(left) === normalizeAppCode(right);
}

function normalizeAppCode(value) {
  return String(value || "").trim().toLowerCase();
}
