import { useCallback, useEffect, useState } from "react";
import { mergePaginatedItems } from "@/shared/hooks/usePaginatedQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { listUserLeaderboards } from "@/features/user-leaderboard/api";
import { useUserLeaderboardAbilities } from "@/features/user-leaderboard/permissions.js";

const pageSize = 50;

export function useUserLeaderboardPage() {
    const abilities = useUserLeaderboardAbilities();
    const { showToast } = useToast();
    const [boardType, setBoardType] = useState("sent");
    const [period, setPeriod] = useState("today");
    const [page, setPage] = useState(1);
    const [data, setData] = useState(emptyData());
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(false);

    const reload = useCallback(async () => {
        setLoading(true);
        setError("");
        try {
            const nextData = await listUserLeaderboards({
                board_type: boardType,
                page,
                page_size: pageSize,
                period,
            });
            setData((current) => {
                const nextPage = Number(nextData?.page || page || 1);
                const nextItems = Array.isArray(nextData?.items) ? nextData.items : [];
                if (nextPage <= 1) {
                    return { ...nextData, items: nextItems, page: nextPage, pageSize: nextData?.pageSize || pageSize };
                }

                return {
                    ...nextData,
                    items: mergePaginatedItems(current.items || [], nextItems),
                    page: nextPage,
                    pageSize: nextData?.pageSize || pageSize,
                };
            });
        } catch (err) {
            const message = err.message || "加载用户榜单失败";
            setError(message);
            showToast(message, "error");
        } finally {
            setLoading(false);
        }
    }, [boardType, page, period, showToast]);

    useEffect(() => {
        void reload();
    }, [reload]);

    const changeBoardType = useCallback((nextValue) => {
        setBoardType(nextValue || "sent");
        setPage(1);
    }, []);

    const changePeriod = useCallback((nextValue) => {
        setPeriod(nextValue || "today");
        setPage(1);
    }, []);

    const resetFilters = useCallback(() => {
        setBoardType("sent");
        setPeriod("today");
        setPage(1);
    }, []);

    useEffect(() => {
        setData(emptyData());
    }, [boardType, period]);

    return {
        abilities,
        boardType,
        changeBoardType,
        changePeriod,
        data,
        error,
        loading: loading && (data.items || []).length === 0,
        page,
        period,
        reload,
        resetFilters,
        setPage,
    };
}

function emptyData() {
    return {
        boardType: "sent",
        endAtMs: 0,
        items: [],
        myRank: null,
        page: 1,
        pageSize,
        period: "today",
        serverTimeMs: 0,
        startAtMs: 0,
        total: 0,
    };
}
