import { useCallback, useEffect, useMemo, useState } from "react";
import { getVipConfig, grantVip, updateVipConfig } from "@/features/vip-config/api";
import { useVipConfigAbilities } from "@/features/vip-config/permissions.js";
import { listResourceGroups } from "@/features/resources/api";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const defaultDurationMs = 30 * 24 * 60 * 60 * 1000;

export function useVipConfigPage() {
    const abilities = useVipConfigAbilities();
    const { showToast } = useToast();
    const [config, setConfig] = useState({ levels: defaultLevels() });
    const [form, setForm] = useState({ levels: defaultLevels().map(levelToForm) });
    const [resourceGroups, setResourceGroups] = useState([]);
    const [drawerOpen, setDrawerOpen] = useState(false);
    const [grantDrawerOpen, setGrantDrawerOpen] = useState(false);
    const [grantForm, setGrantForm] = useState(defaultGrantForm());
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [grantSaving, setGrantSaving] = useState(false);

    const activeCount = useMemo(
        () => (config.levels || []).filter((level) => level.status === "active").length,
        [config.levels],
    );

    const reload = useCallback(async () => {
        setLoading(true);
        try {
            const [remoteConfig, groups] = await Promise.all([
                getVipConfig(),
                listResourceGroups({ page: 1, page_size: 100, status: "active" }),
            ]);
            const levels = completeLevels(remoteConfig.levels || []);
            setConfig({ ...remoteConfig, levels });
            setForm({ levels: levels.map(levelToForm) });
            setResourceGroups(groups.items || []);
        } catch (err) {
            showToast(err.message || "加载 VIP 配置失败", "error");
        } finally {
            setLoading(false);
        }
    }, [showToast]);

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

    const openDrawer = () => {
        setForm({ levels: completeLevels(config.levels || []).map(levelToForm) });
        setDrawerOpen(true);
    };

    const closeDrawer = () => {
        if (saving) {
            return;
        }
        setForm({ levels: completeLevels(config.levels || []).map(levelToForm) });
        setDrawerOpen(false);
    };

    const openGrantDrawer = () => {
        setGrantForm((current) => ({
            ...defaultGrantForm(),
            level: firstActiveLevel(config.levels || []) || current.level || "1",
        }));
        setGrantDrawerOpen(true);
    };

    const closeGrantDrawer = () => {
        if (grantSaving) {
            return;
        }
        setGrantDrawerOpen(false);
        setGrantForm(defaultGrantForm());
    };

    const updateLevel = (levelNumber, patch) => {
        setForm((current) => ({
            ...current,
            levels: (current.levels || []).map((item) => (item.level === levelNumber ? { ...item, ...patch } : item)),
        }));
    };

    const updateGrantForm = (patch) => {
        setGrantForm((current) => ({ ...current, ...patch }));
    };

    const submit = async (event) => {
        event.preventDefault();
        if (!abilities.canUpdate) {
            return;
        }
        let payload;
        try {
            payload = payloadFromForm(form);
        } catch (err) {
            showToast(err.message || "VIP 配置参数不正确", "error");
            return;
        }
        setSaving(true);
        try {
            const saved = await updateVipConfig(payload);
            const levels = completeLevels(saved.levels || []);
            setConfig({ ...saved, levels });
            setForm({ levels: levels.map(levelToForm) });
            setDrawerOpen(false);
            showToast("VIP 配置已保存", "success");
        } catch (err) {
            showToast(err.message || "保存 VIP 配置失败", "error");
        } finally {
            setSaving(false);
        }
    };

    const submitGrant = async (event) => {
        event.preventDefault();
        if (!abilities.canGrant) {
            return;
        }
        const targetUserId = String(grantForm.targetUserId || "").trim();
        const reason = String(grantForm.reason || "").trim();
        const level = Number(grantForm.level || 0);
        if (!targetUserId || !Number.isInteger(level) || level <= 0 || !reason) {
            showToast("VIP 赠送参数不正确", "error");
            return;
        }
        setGrantSaving(true);
        try {
            const result = await grantVip({ targetUserId, level, reason });
            setGrantDrawerOpen(false);
            setGrantForm(defaultGrantForm());
            showToast(`已赠送 ${result.vip?.name || `VIP${level}`}`, "success");
            await reload();
        } catch (err) {
            showToast(err.message || "赠送 VIP 失败", "error");
        } finally {
            setGrantSaving(false);
        }
    };

    return {
        abilities,
        activeCount,
        closeDrawer,
        closeGrantDrawer,
        config,
        drawerOpen,
        form,
        grantDrawerOpen,
        grantForm,
        grantSaving,
        loading,
        openDrawer,
        openGrantDrawer,
        reload,
        resourceGroups,
        saving,
        submit,
        submitGrant,
        updateLevel,
        updateGrantForm,
    };
}

function defaultLevels() {
    return Array.from({ length: 10 }, (_, index) => {
        const level = index + 1;
        return {
            level,
            name: `VIP${level}`,
            status: "disabled",
            priceCoin: 0,
            durationMs: defaultDurationMs,
            rewardResourceGroupId: 0,
            requiredRechargeCoinAmount: 0,
            rechargeGateRequired: level >= 6,
            sortOrder: level * 10,
        };
    });
}

function completeLevels(levels) {
    const byLevel = new Map((levels || []).map((level) => [Number(level.level), level]));
    return defaultLevels().map((fallback) => ({ ...fallback, ...(byLevel.get(fallback.level) || {}) }));
}

function defaultGrantForm() {
    return {
        targetUserId: "",
        level: "1",
        reason: "",
    };
}

function firstActiveLevel(levels) {
    const active = (levels || []).find((level) => level.status === "active");
    return active ? String(active.level) : "";
}

function levelToForm(level) {
    return {
        level: Number(level.level || 0),
        name: level.name || `VIP${level.level}`,
        status: level.status || "disabled",
        priceCoin: level.priceCoin ? String(level.priceCoin) : "",
        durationDays: level.durationMs ? String(Math.max(1, Math.round(Number(level.durationMs) / 86400000))) : "30",
        rewardResourceGroupId: level.rewardResourceGroupId ? String(level.rewardResourceGroupId) : "",
        requiredRechargeCoinAmount: level.requiredRechargeCoinAmount ? String(level.requiredRechargeCoinAmount) : "",
        sortOrder: String(level.sortOrder || Number(level.level || 0) * 10),
    };
}

function payloadFromForm(form) {
    const levels = completeFormLevels(form.levels || []).map((level) => {
        const priceCoin = Number(level.priceCoin || 0);
        const durationDays = Number(level.durationDays || 0);
        const rewardResourceGroupId = Number(level.rewardResourceGroupId || 0);
        const requiredRechargeCoinAmount = level.level >= 6 ? Number(level.requiredRechargeCoinAmount || 0) : 0;
        const sortOrder = Number(level.sortOrder || level.level * 10);
        const status = level.status === "active" ? "active" : "disabled";
        if (!String(level.name || "").trim()) {
            throw new Error(`VIP${level.level} 名称不能为空`);
        }
        if (!Number.isInteger(priceCoin) || priceCoin < 0) {
            throw new Error(`VIP${level.level} 购买金币数不正确`);
        }
        if (!Number.isInteger(durationDays) || durationDays <= 0) {
            throw new Error(`VIP${level.level} 有效天数必须大于 0`);
        }
        if (status === "active" && priceCoin <= 0) {
            throw new Error(`VIP${level.level} 启用时购买金币数必须大于 0`);
        }
        if (status === "active" && rewardResourceGroupId <= 0) {
            throw new Error(`VIP${level.level} 启用时必须选择奖励资源组`);
        }
        if (status === "active" && level.level >= 6 && requiredRechargeCoinAmount <= 0) {
            throw new Error(`VIP${level.level} 启用时必须配置累计充值门槛`);
        }
        return {
            level: Number(level.level),
            name: String(level.name || "").trim(),
            status,
            priceCoin,
            durationMs: durationDays * 86400000,
            rewardResourceGroupId,
            requiredRechargeCoinAmount,
            sortOrder,
        };
    });
    return { levels };
}

function completeFormLevels(levels) {
    const byLevel = new Map((levels || []).map((level) => [Number(level.level), level]));
    return defaultLevels().map((fallback) => ({
        ...levelToForm(fallback),
        ...(byLevel.get(fallback.level) || {}),
    }));
}
