import { useMemo, useState } from "react";
import { getTemporaryPaymentLink, listTemporaryPaymentLinks } from "@/features/payment/api";
import { usePaymentAbilities } from "@/features/payment/permissions.js";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const pageSize = 50;

export function useTemporaryPaymentLinksPage() {
    const abilities = usePaymentAbilities();
    const { showToast } = useToast();
    const [keyword, setKeyword] = useState("");
    const [status, setStatus] = useState("");
    const [providerCode, setProviderCode] = useState("");
    const [page, setPage] = useState(1);
    const [loadingAction, setLoadingAction] = useState("");

    const filters = useMemo(
        () => ({
            keyword,
            provider_code: providerCode,
            status,
        }),
        [keyword, providerCode, status],
    );

    const result = usePaginatedQuery({
        errorMessage: "加载三方临时支付链接失败",
        fetcher: listTemporaryPaymentLinks,
        filters,
        page,
        pageSize,
        queryKey: ["payment", "temporary-links", filters, page],
    });

    const resetPage = (setter) => (value) => {
        setter(value);
        setPage(1);
    };

    const resetFilters = () => {
        setKeyword("");
        setStatus("");
        setProviderCode("");
        setPage(1);
    };

    const verifyOrder = async (orderId) => {
        // 单条核验必须走 admin-server，由 wallet-service 按 provider 重新查询状态；前端只传订单号，避免三方签名参数外露。
        const id = String(orderId || "").trim();
        if (!id || !abilities.canViewTemporaryLink) {
            return null;
        }
        setLoadingAction(`verify:${id}`);
        try {
            const order = await getTemporaryPaymentLink(id);
            await result.reload();
            showToast(order?.status === "paid" ? "支付已成功" : `当前状态：${temporaryStatusLabel(order?.status)}`, "success");
            return order;
        } catch (err) {
            showToast(err.message || "验证支付状态失败", "error");
            return null;
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        data: result.data,
        error: result.error,
        keyword,
        loading: result.loading,
        loadingAction,
        page,
        pageSize,
        providerCode,
        reload: result.reload,
        resetFilters,
        setKeyword: resetPage(setKeyword),
        setPage,
        setProviderCode: resetPage(setProviderCode),
        setStatus: resetPage(setStatus),
        status,
        verifyOrder,
    };
}

export function temporaryStatusLabel(value) {
    if (value === "paid") {
        return "已支付";
    }
    if (value === "redirected") {
        return "已生成链接";
    }
    if (value === "pending") {
        return "待支付";
    }
    if (value === "failed") {
        return "失败";
    }
    if (value === "credited") {
        return "已入账";
    }
    return value || "-";
}
