import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { AppUserListPage } from "./AppUserListPage.jsx";
import { useAppUsersPage } from "@/features/app-users/hooks/useAppUsersPage.js";

const mocks = vi.hoisted(() => ({
    ledgerTable: vi.fn(),
    openCoinLedger: vi.fn(),
}));

vi.mock("@/features/app-users/hooks/useAppUsersPage.js", () => ({
    useAppUsersPage: vi.fn(),
}));

vi.mock("@/features/operations/components/CoinLedgerTable.jsx", () => ({
    CoinLedgerTable: (props) => {
        mocks.ledgerTable(props);
        return <div data-testid="coin-ledger-table">{props.userId}</div>;
    },
}));

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

test("clicking an app user's coin opens the coin ledger drawer", () => {
    vi.mocked(useAppUsersPage).mockReturnValue(pageFixture());

    render(<AppUserListPage />);

    fireEvent.click(screen.getByRole("button", { name: "查看 d 的金币流水" }));

    expect(mocks.openCoinLedger).toHaveBeenCalledWith(expect.objectContaining({ userId: "10001" }));
});

test("coin ledger drawer passes the active app user to the shared ledger table", () => {
    const activeUser = userFixture();
    vi.mocked(useAppUsersPage).mockReturnValue(
        pageFixture({
            activeAction: "coin-ledger",
            activeUser,
        }),
    );

    render(<AppUserListPage />);

    expect(screen.getByTestId("coin-ledger-table")).toHaveTextContent("10001");
    expect(mocks.ledgerTable).toHaveBeenCalledWith(
        expect.objectContaining({ lockedUser: activeUser, userId: "10001" }),
    );
});

function pageFixture(patch = {}) {
    return {
        abilities: {
            canCoinLedger: true,
            canPassword: true,
            canStatus: true,
            canUpdate: true,
            canUpload: true,
            canView: true,
        },
        activeAction: "",
        activeUser: null,
        batchBan: vi.fn(),
        changeLocationFilter: vi.fn(),
        changeQuery: vi.fn(),
        changeSort: vi.fn(),
        changeStatus: vi.fn(),
        changeTimeRange: vi.fn(),
        closeAction: vi.fn(),
        countryForm: { country: "" },
        countryOptions: [],
        data: { items: [userFixture()], page: 1, pageSize: 50, total: 1 },
        editForm: { avatar: "", gender: "", username: "" },
        error: null,
        loading: false,
        loadingAction: "",
        loadingCountries: false,
        loadingRegions: false,
        locationFilterOptions: [],
        locationFilterValue: "",
        openCoinLedger: mocks.openCoinLedger,
        openCountry: vi.fn(),
        openEdit: vi.fn(),
        openPassword: vi.fn(),
        page: 1,
        passwordForm: { password: "" },
        query: "",
        regionOptions: [],
        reload: vi.fn(),
        selectedUserIds: [],
        setCountryForm: vi.fn(),
        setEditForm: vi.fn(),
        setPage: vi.fn(),
        setPasswordForm: vi.fn(),
        setSelectedUserIds: vi.fn(),
        sortBy: "created_at",
        sortDirection: "desc",
        status: "",
        submitCountry: vi.fn(),
        submitEdit: vi.fn(),
        submitPassword: vi.fn(),
        timeRange: { endMs: "", startMs: "" },
        toggleBan: vi.fn(),
        ...patch,
    };
}

function userFixture() {
    return {
        avatar: "",
        coin: 223437,
        country: "AE",
        countryDisplayName: "阿拉伯联合酋长国",
        createdAtMs: 1779322523000,
        displayUserId: "163337",
        lastActiveAtMs: 1781325798000,
        regionId: 2,
        regionName: "中东区",
        status: "active",
        userId: "10001",
        username: "d",
    };
}
