import { useCallback, useEffect, useMemo, useState } from "react";
import {
    getRoomTurnoverRewardConfig,
    listRoomTurnoverRewardSettlements,
    retryRoomTurnoverRewardSettlement,
    updateRoomTurnoverRewardConfig,
} from "@/features/room-turnover-reward/api";
import { useRoomTurnoverRewardAbilities } from "@/features/room-turnover-reward/permissions.js";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { emptyUserIdentityFilter, userIdentityFilterParams } from "@/shared/ui/userIdentityFilter.js";

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

const emptyForm = {
    enabled: false,
    tiers: [],
};

export function useRoomTurnoverRewardPage() {
    const abilities = useRoomTurnoverRewardAbilities();
    const confirm = useConfirm();
    const { showToast } = useToast();
    const [config, setConfig] = useState(null);
    const [configDrawerOpen, setConfigDrawerOpen] = useState(false);
    const [form, setForm] = useState(emptyForm);
    const [configLoading, setConfigLoading] = useState(false);
    const [configSaving, setConfigSaving] = useState(false);
    const [retryingSettlementId, setRetryingSettlementId] = useState("");
    const [query, setQuery] = useState("");
    const [ownerFilter, setOwnerFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [page, setPage] = useState(1);
    const filters = useMemo(
        () => ({
            keyword: query,
            status,
            ...userIdentityFilterParams(ownerFilter, {
                displayUserId: "owner_display_user_id",
                userId: "owner_user_id",
                username: "owner_username",
            }),
        }),
        [ownerFilter, query, status],
    );
    const {
        data: settlements = emptySettlements,
        error: settlementsError,
        loading: settlementsLoading,
        reload: reloadSettlements,
    } = usePaginatedQuery({
        errorMessage: "加载房间流水奖励结算记录失败",
        fetcher: listRoomTurnoverRewardSettlements,
        filters,
        page,
        pageSize,
        queryKey: ["room-turnover-reward-settlements", filters, page],
    });

    const reloadConfig = useCallback(async () => {
        setConfigLoading(true);
        try {
            const nextConfig = await getRoomTurnoverRewardConfig();
            setConfig(nextConfig);
            setForm(formFromConfig(nextConfig));
        } catch (err) {
            showToast(err.message || "加载房间流水奖励配置失败", "error");
        } finally {
            setConfigLoading(false);
        }
    }, [showToast]);

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

    const openConfigDrawer = useCallback(() => {
        setForm(config ? formFromConfig(config) : emptyForm);
        setConfigDrawerOpen(true);
    }, [config]);

    const closeConfigDrawer = useCallback(() => {
        setConfigDrawerOpen(false);
        setForm(config ? formFromConfig(config) : emptyForm);
    }, [config]);

    const changeQuery = (value) => {
        setQuery(value);
        setPage(1);
    };

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

    const changeOwnerFilter = (value) => {
        setOwnerFilter(value);
        setPage(1);
    };

    const submitConfig = async (event) => {
        event.preventDefault();
        if (!abilities.canUpdate) {
            return;
        }
        setConfigSaving(true);
        try {
            const saved = await updateRoomTurnoverRewardConfig(payloadFromForm(form));
            setConfig(saved);
            setForm(formFromConfig(saved));
            setConfigDrawerOpen(false);
            showToast("房间流水奖励配置已保存", "success");
            await reloadSettlements();
        } catch (err) {
            showToast(err.message || "保存房间流水奖励配置失败", "error");
        } finally {
            setConfigSaving(false);
        }
    };

    const retrySettlement = async (settlement) => {
        if (!abilities.canRetry || !settlement?.settlementId) {
            return;
        }
        const accepted = await confirm({
            title: "重试结算",
            message: `确认重试房间 ${settlement.roomId || "-"} 的流水奖励结算？`,
            confirmText: "重试",
        });
        if (!accepted) {
            return;
        }
        setRetryingSettlementId(settlement.settlementId);
        try {
            await retryRoomTurnoverRewardSettlement(settlement.settlementId);
            showToast("房间流水奖励结算已重试", "success");
            await reloadSettlements();
        } catch (err) {
            showToast(err.message || "重试房间流水奖励结算失败", "error");
        } finally {
            setRetryingSettlementId("");
        }
    };

    return {
        abilities,
        changeOwnerFilter,
        changeQuery,
        changeStatus,
        closeConfigDrawer,
        config,
        configDrawerOpen,
        configLoading,
        configSaving,
        form,
        openConfigDrawer,
        ownerFilter,
        page,
        query,
        reloadConfig,
        reloadSettlements,
        retryingSettlementId,
        retrySettlement,
        setForm,
        setPage,
        settlements,
        settlementsError,
        settlementsLoading,
        status,
        submitConfig,
    };
}

function formFromConfig(config) {
    return {
        enabled: Boolean(config?.enabled),
        tiers: (config?.tiers || []).map((tier) => ({
            tierId: tier.tierId || 0,
            tierCode: tier.tierCode || "",
            tierName: tier.tierName || "",
            thresholdCoinSpent: tier.thresholdCoinSpent ? String(tier.thresholdCoinSpent) : "",
            rewardCoinAmount:
                tier.rewardCoinAmount === undefined || tier.rewardCoinAmount === null
                    ? ""
                    : String(tier.rewardCoinAmount),
            status: tier.status || "active",
            sortOrder: String(tier.sortOrder || 0),
        })),
    };
}

function payloadFromForm(form) {
    const tiers = (form.tiers || []).map((tier, index) => {
        const thresholdCoinSpent = Number(tier.thresholdCoinSpent || 0);
        const rewardCoinAmount = Number(tier.rewardCoinAmount || 0);
        if (thresholdCoinSpent <= 0) {
            throw new Error("流水阈值必须大于 0");
        }
        if (rewardCoinAmount < 0) {
            throw new Error("奖励金币不能小于 0");
        }
        const existingTier = Number(tier.tierId || 0) > 0;
        const tierCode = String(tier.tierCode || "").trim() || `room_turnover_${Date.now()}_${index + 1}`;
        const tierName =
            existingTier && String(tier.tierName || "").trim()
                ? String(tier.tierName).trim()
                : `房间流水 ${thresholdCoinSpent}`;
        return {
            tier_id: Number(tier.tierId || 0),
            tier_code: tierCode,
            tier_name: tierName,
            threshold_coin_spent: thresholdCoinSpent,
            reward_coin_amount: rewardCoinAmount,
            status: tier.status === "inactive" ? "inactive" : "active",
            sort_order: index,
        };
    });
    const activeTiers = tiers
        .filter((tier) => tier.status === "active")
        .sort((left, right) => left.sort_order - right.sort_order);
    for (let index = 1; index < activeTiers.length; index += 1) {
        if (activeTiers[index].threshold_coin_spent <= activeTiers[index - 1].threshold_coin_spent) {
            throw new Error("启用档位的流水阈值必须递增");
        }
    }
    if (form.enabled && activeTiers.length === 0) {
        throw new Error("开启后至少需要一个启用档位");
    }
    return {
        enabled: Boolean(form.enabled),
        tiers,
    };
}
