import { fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import { expect, test, vi } from "vitest";
import { GiftSelectField } from "./GiftSelectDrawer.jsx";

vi.mock("@/shared/ui/SideDrawer.jsx", () => ({
    SideDrawer({ 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}
            </aside>
        );
    },
}));

const gifts = [
    {
        chargeAssetType: "COIN",
        coinPrice: 10,
        giftId: "10001",
        giftTypeCode: "normal",
        name: "Rose Gift",
        resource: { previewUrl: "https://media.haiyihy.com/rose.png", resourceCode: "rose_resource" },
        resourceId: 11,
    },
    {
        chargeAssetType: "COIN",
        coinPrice: 20,
        giftId: "10002",
        giftTypeCode: "normal",
        name: "Lucky Star",
        resource: { resourceCode: "lucky_star_resource" },
        resourceId: 12,
    },
];

test("gift select field opens right drawer and writes selected gift id", () => {
    const changes = [];

    function Harness() {
        const [value, setValue] = useState("");
        return (
            <GiftSelectField
                gifts={gifts}
                value={value}
                onChange={(nextValue, gift) => {
                    changes.push({ gift, value: nextValue });
                    setValue(nextValue);
                }}
            />
        );
    }

    render(<Harness />);

    fireEvent.click(screen.getByPlaceholderText("请选择礼物"));

    expect(screen.getByRole("dialog", { name: "选择礼物" })).toHaveAttribute("data-z-index", "1600");
    expect(screen.getByText("Rose Gift")).toBeInTheDocument();

    fireEvent.change(screen.getByPlaceholderText("搜索礼物名称、礼物 ID、资源编码"), {
        target: { value: "star" },
    });

    expect(screen.queryByText("Rose Gift")).not.toBeInTheDocument();
    fireEvent.click(screen.getByText("Lucky Star"));

    expect(changes.at(-1)).toMatchObject({ value: "10002", gift: { giftId: "10002", name: "Lucky Star" } });
    expect(screen.getByDisplayValue("Lucky Star")).toBeInTheDocument();
    expect(screen.queryByRole("dialog", { name: "选择礼物" })).not.toBeInTheDocument();
});
