import { useMemo, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import {
    approveCoinSellerSubApplication,
    listCoinSellerSubApplications,
    rejectCoinSellerSubApplication,
} from "@/features/host-org/api";
import { useCoinSellerSubApplicationAbilities } from "@/features/host-org/permissions.js";
import { coinSellerSubApplicationReviewSchema } from "@/features/host-org/schema";

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

const emptyReviewForm = (decision = "approved") => ({
    commandId: makeCommandId(`coin-seller-sub-${decision}`),
    reason: "",
});

export function useHostSubCoinSellerApplicationsPage() {
    const abilities = useCoinSellerSubApplicationAbilities();
    const { showToast } = useToast();
    const [keyword, setKeyword] = useState("");
    const [status, setStatus] = useState("pending");
    const [parentUserId, setParentUserId] = useState("");
    const [targetUserId, setTargetUserId] = useState("");
    const [page, setPage] = useState(1);
    const [activeAction, setActiveAction] = useState("");
    const [selectedApplication, setSelectedApplication] = useState(null);
    const [reviewDecision, setReviewDecision] = useState("approved");
    const [reviewForm, setReviewForm] = useState(emptyReviewForm);
    const [loadingAction, setLoadingAction] = useState("");
    const filters = useMemo(
        () => ({
            keyword,
            parent_user_id: parentUserId,
            status,
            target_user_id: targetUserId,
        }),
        [keyword, parentUserId, status, targetUserId],
    );
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载子币商申请列表失败",
        fetcher: listCoinSellerSubApplications,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "coin-seller-sub-applications", filters, page],
    });

    const changeKeyword = (value) => {
        setKeyword(value);
        setPage(1);
    };

    const changeStatus = (value) => {
        setStatus(value);
        setPage(1);
    };

    const changeParentUserId = (value) => {
        setParentUserId(String(value || "").trim());
        setPage(1);
    };

    const changeTargetUserId = (value) => {
        setTargetUserId(String(value || "").trim());
        setPage(1);
    };

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

    const openReview = (application, decision) => {
        if (!application?.applicationId || !abilities.canAudit || application.status !== "pending") {
            return;
        }
        // 审核 commandId 与列表刷新分离，避免弹窗重复提交时把另一次审核误认为同一请求。
        setSelectedApplication(application);
        setReviewDecision(decision);
        setReviewForm(emptyReviewForm(decision));
        setActiveAction("review");
    };

    const closeAction = () => {
        setActiveAction("");
        setSelectedApplication(null);
    };

    const submitReview = async (event) => {
        event.preventDefault();
        if (!selectedApplication?.applicationId || !abilities.canAudit) {
            return;
        }
        const payload = parseForm(coinSellerSubApplicationReviewSchema, reviewForm);
        const submitter =
            reviewDecision === "approved" ? approveCoinSellerSubApplication : rejectCoinSellerSubApplication;
        setLoadingAction(`review-${selectedApplication.applicationId}`);
        try {
            await submitter(selectedApplication.applicationId, payload);
            showToast(reviewDecision === "approved" ? "子币商申请已通过" : "子币商申请已拒绝", "success");
            closeAction();
            await reload();
        } catch (err) {
            showToast(err.message || "审核子币商申请失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        activeAction,
        changeKeyword,
        changeParentUserId,
        changeStatus,
        changeTargetUserId,
        closeAction,
        data,
        error,
        keyword,
        loading,
        loadingAction,
        openReview,
        page,
        parentUserId,
        resetFilters,
        reviewDecision,
        reviewForm,
        selectedApplication,
        setPage,
        setReviewForm,
        status,
        submitReview,
        targetUserId,
    };
}

function makeCommandId(prefix) {
    return `${prefix}-${Date.now()}`;
}
