import { useCallback, useEffect, useMemo, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import {
    getLuckyGiftConfig,
    getLuckyGiftDrawSummary,
    listLuckyGiftConfigs,
    updateLuckyGiftConfig,
} from "@/features/lucky-gift/api";
import { emptyLuckyGiftForm, formFromConfig, payloadFromLuckyGiftForm } from "@/features/lucky-gift/configModel.js";
import { useLuckyGiftAbilities } from "@/features/lucky-gift/permissions.js";
import { luckyGiftConfigFormSchema } from "@/features/lucky-gift/schema";

const defaultPoolId = "default";
const emptySummary = {
    actualRTPPPM: 0,
    activitySubsidyCoins: 0,
    baseRewardCoins: 0,
    failedDraws: 0,
    grantedDraws: 0,
    pendingDraws: 0,
    poolId: defaultPoolId,
    roomAtmosphereRewardCoins: 0,
    totalDraws: 0,
    totalRewardCoins: 0,
    totalSpentCoins: 0,
    uniqueRooms: 0,
    uniqueUsers: 0,
};

export function useLuckyGiftPage() {
    const abilities = useLuckyGiftAbilities();
    const { showToast } = useToast();
    const [config, setConfig] = useState(null);
    const [configs, setConfigs] = useState([]);
    const [configDrawerOpen, setConfigDrawerOpen] = useState(false);
    const [addPoolOpen, setAddPoolOpen] = useState(false);
    const [addPoolId, setAddPoolId] = useState("");
    const [form, setForm] = useState(emptyLuckyGiftForm());
    const [configLoading, setConfigLoading] = useState(false);
    const [configSaving, setConfigSaving] = useState(false);
    const [poolId, setPoolId] = useState(defaultPoolId);
    const [giftId, setGiftId] = useState("");
    const [userId, setUserId] = useState("");
    const [roomId, setRoomId] = useState("");
    const [status, setStatus] = useState("");
    const [drawSummary, setDrawSummary] = useState(emptySummary);
    const [drawSummaryLoading, setDrawSummaryLoading] = useState(false);
    const [drawSummaryError, setDrawSummaryError] = useState("");

    const drawFilters = useMemo(
        () => ({ gift_id: giftId, pool_id: poolId, room_id: roomId, status, user_id: userId }),
        [giftId, poolId, roomId, status, userId],
    );
    const poolOptions = useMemo(() => {
        const ids = new Set([poolId]);
        for (const item of configs) {
            if (item.poolId) {
                ids.add(item.poolId);
            }
        }
        return Array.from(ids);
    }, [configs, poolId]);

    const reloadDrawSummary = useCallback(async () => {
        setDrawSummaryLoading(true);
        setDrawSummaryError("");
        try {
            const summary = await getLuckyGiftDrawSummary(drawFilters);
            setDrawSummary(summary);
        } catch (err) {
            setDrawSummaryError(err.message || "加载幸运礼物抽奖汇总失败");
        } finally {
            setDrawSummaryLoading(false);
        }
    }, [drawFilters]);

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

    const reloadConfigs = useCallback(async () => {
        try {
            const nextConfigs = await listLuckyGiftConfigs();
            setConfigs(nextConfigs);
        } catch (err) {
            showToast(err.message || "加载幸运礼物奖池失败", "error");
        }
    }, [showToast]);

    const reloadConfig = useCallback(async () => {
        setConfigLoading(true);
        try {
            const nextConfig = await getLuckyGiftConfig(poolId);
            setConfig(nextConfig);
            setForm(formFromConfig(nextConfig));
        } catch (err) {
            showToast(err.message || "加载幸运礼物配置失败", "error");
        } finally {
            setConfigLoading(false);
        }
    }, [poolId, showToast]);

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

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

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

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

    const submitConfig = async (event) => {
        event.preventDefault();
        if (!abilities.canUpdate) {
            return;
        }
        setConfigSaving(true);
        try {
            const parsed = parseForm(luckyGiftConfigFormSchema, form);
            const saved = await updateLuckyGiftConfig(payloadFromLuckyGiftForm(parsed, config));
            setConfig(saved);
            setConfigs((current) => mergeConfigList(current, saved));
            setForm(formFromConfig(saved));
            setPoolId(saved.poolId || poolId);
            setConfigDrawerOpen(false);
            showToast("幸运礼物配置已保存", "success");
            await reloadDrawSummary();
        } catch (err) {
            showToast(err.message || "保存幸运礼物配置失败", "error");
        } finally {
            setConfigSaving(false);
        }
    };

    const changeGiftId = (value) => {
        setGiftId(value);
    };
    const changePoolId = (value) => {
        setPoolId(value.trim() || defaultPoolId);
    };
    const openAddPool = () => {
        setAddPoolId("");
        setAddPoolOpen(true);
    };
    const closeAddPool = () => {
        setAddPoolOpen(false);
        setAddPoolId("");
    };
    const submitAddPool = (event) => {
        event.preventDefault();
        const nextPoolID = addPoolId.trim();
        if (!nextPoolID) {
            showToast("奖池 ID 不能为空", "error");
            return;
        }
        setPoolId(nextPoolID);
        setConfig(null);
        setForm({ ...emptyLuckyGiftForm(), poolId: nextPoolID });
        setAddPoolOpen(false);
        setAddPoolId("");
        setConfigDrawerOpen(true);
    };
    const changeUserId = (value) => {
        setUserId(value);
    };
    const changeRoomId = (value) => {
        setRoomId(value);
    };
    const changeStatus = (value) => {
        setStatus(value);
    };
    const resetDrawFilters = () => {
        setGiftId("");
        setUserId("");
        setRoomId("");
        setStatus("");
    };

    return {
        abilities,
        addPoolId,
        addPoolOpen,
        changeGiftId,
        changePoolId,
        changeRoomId,
        changeStatus,
        changeUserId,
        closeConfigDrawer,
        closeAddPool,
        config,
        configDrawerOpen,
        configLoading,
        configSaving,
        drawSummary,
        drawSummaryError,
        drawSummaryLoading,
        form,
        giftId,
        openConfigDrawer,
        openAddPool,
        poolId,
        poolOptions,
        reloadConfig,
        reloadConfigs,
        reloadDrawSummary,
        resetDrawFilters,
        roomId,
        setForm,
        setAddPoolId,
        status,
        submitConfig,
        submitAddPool,
        userId,
    };
}

function mergeConfigList(configs, saved) {
    const out = [];
    let replaced = false;
    for (const item of configs) {
        if (item.poolId === saved.poolId) {
            out.push(saved);
            replaced = true;
            continue;
        }
        out.push(item);
    }
    if (!replaced) {
        out.unshift(saved);
    }
    return out;
}
