import { useCallback, useEffect, useMemo, useState } from "react";
import {
    getInviteActivityRewardConfig,
    listInviteActivityRewardSummaries,
    updateInviteActivityRewardConfig,
} from "@/features/invite-activity-reward/api";
import { useInviteActivityRewardAbilities } from "@/features/invite-activity-reward/permissions.js";
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 emptySummaries = { items: [], page: 1, pageSize, total: 0 };
const emptyForm = {
    enabled: true,
    perInviteInviterRewardCoinAmount: "",
    perInviteInviteeRewardCoinAmount: "",
    tiers: [],
};

export function useInviteActivityRewardPage() {
    const abilities = useInviteActivityRewardAbilities();
    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 [userFilter, setUserFilter] = useState(emptyUserIdentityFilter);
    const [cycleKey, setCycleKey] = useState("");
    const [page, setPage] = useState(1);
    const filters = useMemo(
        () => ({ cycle_key: cycleKey, ...userIdentityFilterParams(userFilter) }),
        [cycleKey, userFilter],
    );
    const {
        data: summaries = emptySummaries,
        error: summariesError,
        loading: summariesLoading,
        reload: reloadSummaries,
    } = usePaginatedQuery({
        errorMessage: "加载邀请活动列表失败",
        fetcher: listInviteActivityRewardSummaries,
        filters,
        page,
        pageSize,
        queryKey: ["invite-activity-reward-summaries", filters, page],
    });

    const reloadConfig = useCallback(async () => {
        setConfigLoading(true);
        try {
            const loaded = await getInviteActivityRewardConfig();
            setConfig(loaded);
            setForm(formFromConfig(loaded));
        } 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 changeUserFilter = (value) => {
        setUserFilter(value);
        setPage(1);
    };
    const changeCycleKey = (value) => {
        setCycleKey(value);
        setPage(1);
    };
    const submitConfig = async (event) => {
        event.preventDefault();
        if (!abilities.canUpdate) {
            return;
        }
        setConfigSaving(true);
        try {
            const saved = await updateInviteActivityRewardConfig(payloadFromForm(form));
            setConfig(saved);
            setForm(formFromConfig(saved));
            setConfigDrawerOpen(false);
            showToast("邀请活动配置已保存", "success");
            await reloadSummaries();
        } catch (err) {
            showToast(err.message || "保存邀请活动配置失败", "error");
        } finally {
            setConfigSaving(false);
        }
    };

    return {
        abilities,
        changeCycleKey,
        changeUserFilter,
        closeConfigDrawer,
        config,
        configDrawerOpen,
        configLoading,
        configSaving,
        cycleKey,
        form,
        openConfigDrawer,
        page,
        reloadConfig,
        setForm,
        setPage,
        reloadSummaries,
        summaries,
        summariesError,
        summariesLoading,
        submitConfig,
        userFilter,
    };
}

function formFromConfig(config) {
    return {
        enabled: Boolean(config.enabled),
        perInviteInviterRewardCoinAmount: config.perInviteInviterRewardCoinAmount
            ? String(config.perInviteInviterRewardCoinAmount)
            : "",
        perInviteInviteeRewardCoinAmount: config.perInviteInviteeRewardCoinAmount
            ? String(config.perInviteInviteeRewardCoinAmount)
            : "",
        tiers: (config.tiers || []).map((tier) => ({
            tierId: tier.tierId || 0,
            rewardType: tier.rewardType || "recharge",
            tierCode: tier.tierCode || "",
            tierName: tier.tierName || "",
            thresholdCoinAmount: tier.thresholdCoinAmount ? String(tier.thresholdCoinAmount) : "",
            thresholdValidInviteCount: tier.thresholdValidInviteCount ? String(tier.thresholdValidInviteCount) : "",
            rewardCoinAmount: tier.rewardCoinAmount ? String(tier.rewardCoinAmount) : "",
            status: tier.status || "active",
            sortOrder: String(tier.sortOrder || 0),
        })),
    };
}

function payloadFromForm(form) {
    const perInviteInviterRewardCoinAmount = Number(form.perInviteInviterRewardCoinAmount || 0);
    const perInviteInviteeRewardCoinAmount = Number(form.perInviteInviteeRewardCoinAmount || 0);
    if (perInviteInviterRewardCoinAmount < 0 || perInviteInviteeRewardCoinAmount < 0) {
        throw new Error("每邀请一人奖励金币不能小于 0");
    }
    const tiers = (form.tiers || []).map((tier, index) => {
        const rewardType = tier.rewardType === "valid_invite" ? "valid_invite" : "recharge";
        const thresholdCoinAmount = rewardType === "recharge" ? Number(tier.thresholdCoinAmount || 0) : 0;
        const thresholdValidInviteCount =
            rewardType === "valid_invite" ? Number(tier.thresholdValidInviteCount || 0) : 0;
        const rewardCoinAmount = Number(tier.rewardCoinAmount || 0);
        if (rewardType === "recharge" && thresholdCoinAmount <= 0) {
            throw new Error("累计充值金币门槛必须大于 0");
        }
        if (rewardType === "valid_invite" && thresholdValidInviteCount <= 0) {
            throw new Error("Valid users threshold must be greater than 0");
        }
        if (rewardCoinAmount <= 0) {
            throw new Error("奖励金币必须大于 0");
        }
        const tierCode = normalizeTierCode(tier.tierCode, rewardType, index);
        const tierName =
            rewardType === "recharge"
                ? `Cumulative Recharge ${formatNumber(thresholdCoinAmount)} coins`
                : `Valid Users ${formatNumber(thresholdValidInviteCount)} people`;
        return {
            tier_id: Number(tier.tierId || 0),
            reward_type: rewardType,
            tier_code: tierCode,
            tier_name: tierName,
            threshold_coin_amount: thresholdCoinAmount,
            threshold_valid_invite_count: thresholdValidInviteCount,
            reward_coin_amount: rewardCoinAmount,
            status: tier.status === "inactive" ? "inactive" : "active",
            sort_order: index,
        };
    });
    if (
        form.enabled &&
        tiers.filter((tier) => tier.status === "active").length === 0 &&
        perInviteInviterRewardCoinAmount <= 0 &&
        perInviteInviteeRewardCoinAmount <= 0
    ) {
        throw new Error("开启后至少需要一个启用档位或每邀请一人奖励");
    }
    return {
        enabled: Boolean(form.enabled),
        per_invite_inviter_reward_coin_amount: perInviteInviterRewardCoinAmount,
        per_invite_invitee_reward_coin_amount: perInviteInviteeRewardCoinAmount,
        tiers,
    };
}

function formatNumber(value) {
    return new Intl.NumberFormat("en-US").format(Number(value || 0));
}

function normalizeTierCode(value, rewardType, index) {
    const code = String(value || "").trim();
    if (code && !/[\u3400-\u9fff]/.test(code)) {
        return code;
    }
    return `invite_${rewardType}_${Date.now()}_${index + 1}`;
}
