import { useCallback, useState } from "react";
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 abilities = useAppConfigAbilities();
  const confirm = useConfirm();
  const { showToast } = useToast();
  const [activeAction, setActiveAction] = useState("");
  const [editingItem, setEditingItem] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [loadingAction, setLoadingAction] = useState("");
  const queryFn = useCallback(() => listH5Links(), []);
  const { data = emptyData, error, loading, reload } = useAdminQuery(queryFn, {
    errorMessage: "加载 H5 配置失败",
    initialData: emptyData,
    queryKey: ["app-config", "h5-links"]
  });

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

  const openEdit = (item) => {
    setEditingItem(item);
    setForm({ key: item.key || "", label: item.label || "", url: item.url || "" });
    setActiveAction("edit");
  };

  const closeEdit = () => {
    setActiveAction("");
    setEditingItem(null);
    setForm(emptyForm());
  };

  const submitEdit = async (event) => {
    event.preventDefault();
    if (!editingItem) {
      const payload = parseForm(h5LinkUpdateSchema, form);
      setLoadingAction("create");
      try {
        await createH5Link(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(editingItem.key, payload);
      closeEdit();
      await reload();
      showToast("H5配置已更新", "success");
    } catch (err) {
      showToast(err.message || "操作失败", "error");
    } finally {
      setLoadingAction("");
    }
  };

  const removeH5Link = async (item) => {
    const ok = await confirm({
      confirmText: "删除",
      message: item.label || item.key,
      title: "删除H5配置",
      tone: "danger"
    });
    if (!ok) {
      return;
    }
    setLoadingAction(`delete:${item.key}`);
    try {
      await deleteH5Link(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
  };
}
