import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { AppProviders } from "@/app/providers.jsx";
import { RoomRpsConfigPage } from "./RoomRpsConfigPage.jsx";

vi.mock("@/app/auth/AuthProvider.jsx", () => ({
    AuthProvider: ({ children }) => children,
    useAuth: () => ({ can: () => true }),
}));

vi.mock("@/shared/ui/SideDrawer.jsx", () => ({
    SideDrawer({ actions, children, drawerProps, onClose, open, title }) {
        if (!open) {
            return null;
        }
        return (
            <aside aria-label={title} data-z-index={drawerProps?.sx?.zIndex} role="dialog">
                <button type="button" onClick={onClose}>
                    关闭
                </button>
                {children}
                {actions}
            </aside>
        );
    },
}));

const patchBodies = [];

beforeEach(() => {
    patchBodies.length = 0;
    vi.stubGlobal("fetch", vi.fn(mockFetch));
});

afterEach(() => {
    vi.unstubAllGlobals();
});

test("room rps gift tier uses gift preview card drawer selection before saving", async () => {
    const user = userEvent.setup();

    render(
        <AppProviders>
            <MemoryRouter>
                <RoomRpsConfigPage />
            </MemoryRouter>
        </AppProviders>,
    );

    expect(await screen.findByText("房内猜拳")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "编辑" }));
    expect(await screen.findByRole("dialog", { name: "房内猜拳配置" })).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: /第 1 档礼物 Rock Rose/ }));

    expect(screen.getByRole("dialog", { name: "选择第 1 档礼物" })).toHaveAttribute("data-z-index", "1600");
    expect(screen.getByText("Invalid Alpha Gift")).toBeInTheDocument();
    await user.click(screen.getByText("Invalid Alpha Gift"));

    expect(screen.getByRole("button", { name: /第 1 档礼物 Invalid Alpha Gift/ })).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "保存配置" }));

    await waitFor(() => expect(patchBodies).toHaveLength(1));
    expect(patchBodies[0].stakeGifts[0]).toMatchObject({
        enabled: true,
        giftId: "Gifi-3",
        sortOrder: 1,
    });
});

async function mockFetch(input, init = {}) {
    const url = String(input);
    const method = init.method || "GET";

    if (url.includes("/v1/admin/game/room-rps/config") && method === "GET") {
        return jsonResponse({
            config: {
                challengeTimeoutMs: 600000,
                gameId: "room_rps",
                revealCountdownMs: 3000,
                stakeGifts: [
                    { enabled: true, giftId: "10001", giftName: "Rock Rose", sortOrder: 1 },
                    { enabled: true, giftId: "10002", giftName: "Paper Bell", sortOrder: 2 },
                    { enabled: true, giftId: "10003", giftName: "Scissor Crown", sortOrder: 3 },
                    { enabled: true, giftId: "10004", giftName: "Victory Cup", sortOrder: 4 },
                ],
                status: "active",
            },
        });
    }

    if (url.includes("/v1/admin/gifts")) {
        return jsonResponse({
            items: [
                {
                    coinPrice: 10,
                    giftId: "10001",
                    giftTypeCode: "normal",
                    name: "Rock Rose",
                    resource: { previewUrl: "https://cdn.example.com/rock.webp", resourceCode: "rock_rose" },
                    resourceId: 11,
                },
                {
                    coinPrice: 20,
                    giftId: "10005",
                    giftTypeCode: "normal",
                    name: "Lucky Star",
                    resource: { previewUrl: "https://cdn.example.com/lucky.webp", resourceCode: "lucky_star" },
                    resourceId: 12,
                },
                {
                    coinPrice: 1,
                    giftId: "Gifi-3",
                    giftTypeCode: "normal",
                    name: "Invalid Alpha Gift",
                    resource: { previewUrl: "https://cdn.example.com/invalid.webp", resourceCode: "invalid_alpha" },
                    resourceId: 13,
                },
            ],
            page: 1,
            pageSize: 200,
            total: 2,
        });
    }

    if (url.includes("/v1/admin/game/room-rps/config") && method === "PATCH") {
        const body = JSON.parse(String(init.body || "{}"));
        patchBodies.push(body);
        return jsonResponse({
            config: {
                ...body,
                gameId: "room_rps",
                stakeGifts: body.stakeGifts.map((gift) => ({
                    ...gift,
                    giftId: String(gift.giftId),
                })),
            },
        });
    }

    return jsonResponse(null);
}

function jsonResponse(data) {
    return new Response(JSON.stringify({ code: 0, data }), { status: 200 });
}
