import { useMemo, useState } from "react";
import { listHostWithdrawals } from "@/features/host-org/api";
import { useHostWithdrawalAbilities } from "@/features/host-org/permissions.js";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";

const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };
const emptyTimeRange = { endMs: "", startMs: "" };

export function useHostWithdrawalsPage() {
    const abilities = useHostWithdrawalAbilities();
    const [page, setPage] = useState(1);
    const [recordType, setRecordType] = useState("");
    const [identity, setIdentity] = useState("");
    const [status, setStatus] = useState("");
    const [keyword, setKeyword] = useState("");
    const [timeRange, setTimeRange] = useState(emptyTimeRange);
    const filters = useMemo(
        () => ({
            end_at_ms: timeRange.endMs || "",
            identity,
            keyword,
            record_type: recordType,
            start_at_ms: timeRange.startMs || "",
            status,
        }),
        [identity, keyword, recordType, status, timeRange.endMs, timeRange.startMs],
    );
    const query = usePaginatedQuery({
        errorMessage: "加载主播提现列表失败",
        fetcher: listHostWithdrawals,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "host-withdrawals", filters, page],
    });
    const data = query.data || emptyData;
    const hasActiveFilters = Boolean(recordType || identity || status || keyword || timeRange.startMs || timeRange.endMs);

    const changeRecordType = (value) => {
        setRecordType(value);
        setPage(1);
    };
    const changeIdentity = (value) => {
        setIdentity(value);
        setPage(1);
    };
    const changeStatus = (value) => {
        setStatus(value);
        setPage(1);
    };
    const changeKeyword = (value) => {
        setKeyword(value);
        setPage(1);
    };
    const changeTimeRange = (nextRange) => {
        setTimeRange(nextRange);
        setPage(1);
    };
    const resetFilters = () => {
        setRecordType("");
        setIdentity("");
        setStatus("");
        setKeyword("");
        setTimeRange(emptyTimeRange);
        setPage(1);
    };

    return {
        abilities,
        changeIdentity,
        changeKeyword,
        changeRecordType,
        changeStatus,
        changeTimeRange,
        data,
        error: query.error,
        hasActiveFilters,
        identity,
        keyword,
        loading: query.loading,
        page,
        recordType,
        reload: query.reload,
        resetFilters,
        setPage,
        status,
        timeRange,
    };
}
