import { useCallback, useEffect, useMemo, useState } from "react";
import { listResourceGroups } from "@/features/resources/api";
import {
    getFirstRechargeRewardConfig,
    listFirstRechargeRewardClaims,
    updateFirstRechargeRewardConfig,
} from "@/features/first-recharge-reward/api";
import { useFirstRechargeRewardAbilities } from "@/features/first-recharge-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 emptyClaims = { items: [], page: 1, pageSize, total: 0 };

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

export function useFirstRechargeRewardPage() {
    const abilities = useFirstRechargeRewardAbilities();
    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 [resourceGroups, setResourceGroups] = useState([]);
    const [userFilter, setUserFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [page, setPage] = useState(1);
    const filters = useMemo(() => ({ status, ...userIdentityFilterParams(userFilter) }), [status, userFilter]);
    const {
        data: claims = emptyClaims,
        error: claimsError,
        loading: claimsLoading,
        reload: reloadClaims,
    } = usePaginatedQuery({
        errorMessage: "加载首充礼包记录失败",
        fetcher: listFirstRechargeRewardClaims,
        filters,
        page,
        pageSize,
        queryKey: ["first-recharge-reward-claims", filters, page],
    });

    const reloadConfig = useCallback(async () => {
        setConfigLoading(true);
        try {
            const [config, groups] = await Promise.all([
                getFirstRechargeRewardConfig(),
                listResourceGroups({ page: 1, page_size: 100, status: "active" }),
            ]);
            setConfig(config);
            setForm(formFromConfig(config));
            setResourceGroups(groups.items || []);
        } 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 changeStatus = (value) => {
        setStatus(value);
        setPage(1);
    };

    const submitConfig = async (event) => {
        event.preventDefault();
        if (!abilities.canUpdate) {
            return;
        }
        setConfigSaving(true);
        try {
            const saved = await updateFirstRechargeRewardConfig(payloadFromForm(form));
            setConfig(saved);
            setForm(formFromConfig(saved));
            setConfigDrawerOpen(false);
            showToast("首充礼包配置已保存", "success");
            await reloadClaims();
        } catch (err) {
            showToast(err.message || "保存首充礼包配置失败", "error");
        } finally {
            setConfigSaving(false);
        }
    };

    return {
        abilities,
        changeUserFilter,
        changeStatus,
        claims,
        claimsError,
        claimsLoading,
        closeConfigDrawer,
        config,
        configDrawerOpen,
        configLoading,
        configSaving,
        form,
        openConfigDrawer,
        page,
        reloadClaims,
        reloadConfig,
        resourceGroups,
        setForm,
        setPage,
        status,
        submitConfig,
        userFilter,
    };
}

function formFromConfig(config) {
    return {
        enabled: Boolean(config.enabled),
        tiers: (config.tiers || []).map((tier) => ({
            tierId: tier.tierId || 0,
            tierCode: tier.tierCode || "",
            tierName: tier.tierName || "",
            usdAmount: tier.usdMinorAmount ? (tier.usdMinorAmount / 100).toFixed(2) : "",
            googleProductId: tier.googleProductId || "",
            discountPercent: String(tier.discountPercent || 0),
            resourceGroupId: tier.resourceGroupId ? String(tier.resourceGroupId) : "",
            status: tier.status || "active",
            sortOrder: String(tier.sortOrder || 0),
        })),
    };
}

function payloadFromForm(form) {
    const seenGoogleProductIds = new Set();
    const tiers = (form.tiers || []).map((tier, index) => {
        const usdMinorAmount = Math.round(Number(tier.usdAmount || 0) * 100);
        const googleProductId = String(tier.googleProductId || "").trim();
        const discountPercent = Number(tier.discountPercent || 0);
        const resourceGroupId = Number(tier.resourceGroupId || 0);
        if (usdMinorAmount <= 0) {
            throw new Error("美元档位必须大于 0");
        }
        if (!googleProductId) {
            throw new Error("Google 商品 ID 不能为空");
        }
        const normalizedGoogleProductId = googleProductId.toLowerCase();
        if (seenGoogleProductIds.has(normalizedGoogleProductId)) {
            throw new Error("Google 商品 ID 不能重复");
        }
        seenGoogleProductIds.add(normalizedGoogleProductId);
        if (discountPercent < 0 || discountPercent > 100) {
            throw new Error("优惠百分比必须在 0 到 100 之间");
        }
        if (resourceGroupId <= 0) {
            throw new Error("请选择资源组");
        }
        const tierCode = String(tier.tierCode || "").trim() || `first_recharge_${index + 1}_${usdMinorAmount}`;
        const tierName = String(tier.tierName || "").trim() || `$${(usdMinorAmount / 100).toFixed(2)}`;
        return {
            tier_id: Number(tier.tierId || 0),
            tier_code: tierCode,
            tier_name: tierName,
            min_coin_amount: 0,
            max_coin_amount: 0,
            usd_minor_amount: usdMinorAmount,
            google_product_id: googleProductId,
            discount_percent: discountPercent,
            resource_group_id: resourceGroupId,
            status: tier.status === "inactive" ? "inactive" : "active",
            sort_order: Number(tier.sortOrder || index),
        };
    });
    if (form.enabled && tiers.filter((tier) => tier.status === "active").length === 0) {
        throw new Error("开启后至少需要一个启用档位");
    }
    return {
        enabled: Boolean(form.enabled),
        tiers,
    };
}
