import { useEffect, useMemo, useState } from "react";
import {
    createRechargeProduct,
    deleteRechargeProduct,
    listRechargeProducts,
    updateRechargeProduct,
} from "@/features/payment/api";
import { usePaymentAbilities } from "@/features/payment/permissions.js";
import { rechargeProductSchema } from "@/features/payment/schema";
import { parseForm } from "@/shared/forms/validation";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const pageSize = 50;

// 新建默认走 H5 web 档位和普通用户档位；币商档位必须由运营显式选择，避免误配商品受众。
const emptyForm = () => ({
    amountUsdt: "",
    audienceType: "normal",
    coinAmount: "",
    description: "",
    enabled: true,
    platform: "web",
    productName: "",
    regionIds: [],
});

export function useRechargeProductsPage() {
    const abilities = usePaymentAbilities();
    const confirm = useConfirm();
    const { showToast } = useToast();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [keyword, setKeyword] = useState("");
    const [status, setStatus] = useState("");
    const [platform, setPlatform] = useState("");
    const [audienceType, setAudienceType] = useState("");
    const [regionId, setRegionId] = useState("");
    const [page, setPage] = useState(1);
    const [activeAction, setActiveAction] = useState("");
    const [editingItem, setEditingItem] = useState(null);
    const [form, setFormState] = useState(emptyForm);
    const [loadingAction, setLoadingAction] = useState("");

    // audienceType 直接透传给 admin-server，后台再转 wallet-service 过滤 normal / coin_seller 档位。
    const filters = useMemo(
        () => ({
            audienceType,
            keyword,
            platform,
            regionId,
            status,
        }),
        [audienceType, keyword, platform, regionId, status],
    );
    const result = usePaginatedQuery({
        errorMessage: "加载内购配置失败",
        fetcher: listRechargeProducts,
        filters,
        page,
        pageSize,
        queryKey: ["payment", "recharge-products", filters, page],
    });

    useEffect(() => {
        setPage(1);
    }, [filters]);

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

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

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

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

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

    const submitProduct = async (event) => {
        event.preventDefault();
        let payload;
        try {
            payload = parseForm(rechargeProductSchema, normalizeForm(form));
        } catch (err) {
            showToast(err.message || "表单校验失败", "error");
            return;
        }

        const action = editingItem ? "edit" : "create";
        setLoadingAction(action);
        try {
            if (editingItem) {
                await updateRechargeProduct(editingItem.productId, payload);
                showToast("内购配置已更新", "success");
                closeDialog();
                await result.reload();
            } else {
                const createdProduct = await createRechargeProduct(payload);
                const nextFilters = visibleFiltersForCreatedProduct(createdProduct, payload);
                const canReloadCurrentQuery =
                    page === 1 &&
                    keyword === nextFilters.keyword &&
                    status === nextFilters.status &&
                    platform === nextFilters.platform &&
                    audienceType === nextFilters.audienceType &&
                    regionId === nextFilters.regionId;

                showToast("内购配置已新增", "success");
                closeDialog();

                // 新增币商档位时，当前列表可能还停在“普通用户”过滤条件；这里主动切到新商品所属的受众、
                // 平台和上下架状态，并清空搜索/区域过滤，保证运营提交后能立刻看到刚创建的记录。
                setKeyword(nextFilters.keyword);
                setStatus(nextFilters.status);
                setPlatform(nextFilters.platform);
                setAudienceType(nextFilters.audienceType);
                setRegionId(nextFilters.regionId);
                setPage(1);

                // 如果当前查询条件已经正好能展示新商品，直接刷新当前页；否则交给上面的过滤条件变更触发新查询。
                if (canReloadCurrentQuery) {
                    await result.reload();
                }
            }
        } catch (err) {
            showToast(err.message || "操作失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    const removeProduct = async (item) => {
        const ok = await confirm({
            confirmText: "删除",
            message: item.productName || item.productCode || `内购配置 ${item.productId}`,
            title: "删除内购配置",
            tone: "danger",
        });
        if (!ok) {
            return;
        }
        setLoadingAction(`delete:${item.productId}`);
        try {
            await deleteRechargeProduct(item.productId);
            await result.reload();
            showToast("内购配置已删除", "success");
        } catch (err) {
            showToast(err.message || "删除失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    const toggleProductEnabled = async (item, enabled) => {
        setLoadingAction(`status:${item.productId}`);
        try {
            await updateRechargeProduct(item.productId, productPayloadFromItem(item, enabled));
            await result.reload();
            showToast(enabled ? "内购配置已上架" : "内购配置已下架", "success");
        } catch (err) {
            showToast(err.message || "状态更新失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        activeAction,
        audienceType,
        closeDialog,
        data: result.data,
        editingItem,
        error: result.error,
        form,
        keyword,
        loading: result.loading,
        loadingAction,
        loadingRegions,
        openCreate,
        openEdit,
        page,
        pageSize,
        platform,
        regionId,
        regionOptions,
        reload: result.reload,
        removeProduct,
        resetFilters,
        setForm,
        setAudienceType,
        setKeyword,
        setPage,
        setPlatform,
        setRegionId,
        setStatus,
        status,
        submitProduct,
        toggleProductEnabled,
    };
}

function normalizeForm(form) {
    return {
        ...form,
        amountUsdt: form.amountUsdt || "",
        audienceType: form.audienceType || "normal",
        coinAmount: form.coinAmount || "",
        regionIds: form.regionIds || [],
    };
}

function formFromProduct(item) {
    // 后端老数据可能没有 audienceType；前端按普通用户兜底，保证旧档位不会被误认为币商档位。
    return {
        amountUsdt: item.amountUsdt || "",
        audienceType: item.audienceType === "coin_seller" ? "coin_seller" : "normal",
        coinAmount: item.coinAmount === 0 || item.coinAmount ? String(item.coinAmount) : "",
        description: item.description || "",
        enabled: item.enabled ?? item.status === "active",
        platform: item.platform || "web",
        productName: item.productName || "",
        regionIds: (item.regionIds || []).map(String),
    };
}

function productPayloadFromItem(item, enabled) {
    // 行内上下架只改变 enabled，其他字段必须按订单快照原样回传，避免一次快捷开关丢失受众或平台。
    return {
        amountUsdt: item.amountUsdt || formatMicroAmount(item.amountUsdtMicro),
        audienceType: item.audienceType === "coin_seller" ? "coin_seller" : "normal",
        coinAmount: item.coinAmount,
        description: item.description || "",
        enabled,
        platform: item.platform === "android" || item.platform === "ios" ? item.platform : "web",
        productName: item.productName || "",
        regionIds: item.regionIds || [],
    };
}

function visibleFiltersForCreatedProduct(product, payload) {
    const enabled = product?.enabled ?? payload.enabled;
    const audienceType =
        product?.audienceType === "coin_seller" || payload.audienceType === "coin_seller" ? "coin_seller" : "normal";
    return {
        audienceType,
        keyword: "",
        platform: normalizeProductPlatform(product?.platform || payload.platform),
        regionId: "",
        status: product?.status === "disabled" || enabled === false ? "disabled" : "active",
    };
}

function normalizeProductPlatform(value) {
    if (value === "android" || value === "ios" || value === "web") {
        return value;
    }
    return "web";
}

function formatMicroAmount(value) {
    const numberValue = Number(value || 0);
    if (!Number.isFinite(numberValue) || numberValue <= 0) {
        return "0";
    }
    return String(numberValue / 1_000_000).replace(/\.?0+$/, "");
}
