import { useCallback, useEffect, useMemo, useState } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { createExploreTab, deleteExploreTab, listExploreTabs, updateExploreTab } from "@/features/app-config/api";
import { useAppConfigAbilities } from "@/features/app-config/permissions.js";
import { exploreTabSchema } 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 = () => ({
    enabled: true,
    h5Url: "",
    sortOrder: "0",
    tab: "",
});

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

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

    useEffect(() => {
        // Explore tab 的文案和 H5 地址属于 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(formFromExploreTab(item));
        setActiveAction("edit");
    };

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

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

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

    const toggleExploreTab = async (item, nextEnabled) => {
        setLoadingAction(`toggle:${item.id}`);
        try {
            await updateExploreTab(appCode, item.id, {
                enabled: nextEnabled,
                h5Url: item.h5Url || "",
                sortOrder: item.sortOrder || 0,
                tab: item.tab || "",
            });
            await reload();
            showToast(nextEnabled ? "Explore tab 已启用" : "Explore tab 已关闭", "success");
        } catch (err) {
            showToast(err.message || "操作失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    const removeExploreTab = async (item) => {
        const ok = await confirm({
            confirmText: "删除",
            message: item.tab || `Explore ${item.id}`,
            title: "删除 Explore tab",
            tone: "danger",
        });
        if (!ok) {
            return;
        }
        setLoadingAction(`delete:${item.id}`);
        try {
            await deleteExploreTab(appCode, item.id);
            await reload();
            showToast("Explore 配置已删除", "success");
        } catch (err) {
            showToast(err.message || "删除失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        activeAction,
        closeDialog,
        data,
        editingItem,
        enabled,
        error,
        form,
        keyword,
        loading,
        loadingAction,
        openCreate,
        openEdit,
        reload,
        removeExploreTab,
        resetFilters,
        setEnabled,
        setForm,
        setKeyword,
        submitExploreTab,
        toggleExploreTab,
    };
}

function normalizeForm(form) {
    return {
        ...form,
        sortOrder: form.sortOrder || 0,
    };
}

function formFromExploreTab(item) {
    return {
        enabled: Boolean(item.enabled),
        h5Url: item.h5Url || "",
        sortOrder: String(item.sortOrder || 0),
        tab: item.tab || "",
    };
}
