import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, expect, test, vi } from "vitest";
import { MemoryRouter } from "react-router-dom";
import { AppUserDetailProvider } from "@/features/app-users/components/AppUserDetailProvider.jsx";
import { AppUserDetailContext } from "@/features/app-users/components/AppUserDetailContext.jsx";
import { setAccessToken } from "@/shared/api/request";
import { ToastProvider } from "@/shared/ui/ToastProvider.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";

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

test("renders avatar name original id and pretty id without label", () => {
    render(
        <AdminUserIdentity
            user={{
                avatar: "https://cdn.example/avatar.png",
                defaultDisplayUserId: "123456",
                displayUserId: "VIP2026",
                prettyDisplayUserId: "VIP2026",
                prettyId: "pretty-2026",
                userId: "10001",
                username: "tester",
            }}
        />,
    );

    expect(screen.getByText("tester")).toBeInTheDocument();
    expect(screen.getByText("123456")).toBeInTheDocument();
    expect(screen.queryByText(["彩色", "靓号"].join(""))).not.toBeInTheDocument();
    expect(screen.getByText("VIP2026")).toBeInTheDocument();
    expect(document.querySelector("img")).toHaveAttribute("src", "https://cdn.example/avatar.png");
});

test("clickable identity opens detail handler", async () => {
    const user = userEvent.setup();
    const onClick = vi.fn();
    render(<AdminUserIdentity onClick={onClick} user={{ displayUserId: "123456", userId: "10001" }} />);

    await user.click(screen.getByRole("button", { name: /查看用户/ }));

    expect(onClick).toHaveBeenCalledTimes(1);
});

test("empty identity renders dash without avatar or click target", () => {
    const onClick = vi.fn();
    render(<AdminUserIdentity onClick={onClick} openInAppUserDetail user={{ displayUserId: "0", userId: "0" }} />);

    expect(screen.getByText("-")).toBeInTheDocument();
    expect(screen.queryByText("0")).not.toBeInTheDocument();
    expect(screen.queryByRole("button")).not.toBeInTheDocument();
});

test("uses original id before pretty id when rows pass current display id", () => {
    render(
        <AdminUserIdentity
            rows={["VIP2026", "10001"]}
            user={{
                defaultDisplayUserId: "123456",
                displayUserId: "VIP2026",
                prettyDisplayUserId: "VIP2026",
                prettyId: "pretty-2026",
                userId: "10001",
                username: "tester",
            }}
        />,
    );

    expect(screen.getByText("123456")).toBeInTheDocument();
    expect(screen.getByText("VIP2026")).toBeInTheDocument();
    expect(screen.getByText("10001")).toBeInTheDocument();
});

test("open detail uses provider instead of app user list link", async () => {
    const user = userEvent.setup();
    const openAppUserDetail = vi.fn();
    render(
        <AppUserDetailContext.Provider value={{ openAppUserDetail }}>
            <AdminUserIdentity openInAppUserDetail user={{ displayUserId: "123456", userId: "10001" }} />
        </AppUserDetailContext.Provider>,
    );

    await user.click(screen.getByRole("button", { name: /查看用户详情/ }));

    expect(screen.queryByRole("link", { name: /跳转用户详情/ })).not.toBeInTheDocument();
    expect(openAppUserDetail).toHaveBeenCalledWith(
        expect.objectContaining({ displayUserId: "123456", userId: "10001" }),
    );
});

test("open detail accepts assigned user id from pretty id records", async () => {
    const user = userEvent.setup();
    const openAppUserDetail = vi.fn();
    render(
        <AppUserDetailContext.Provider value={{ openAppUserDetail }}>
            <AdminUserIdentity
                openInAppUserDetail
                user={{
                    assignedUserId: "10001",
                    displayUserId: "111cc1111",
                    prettyId: "pretty-2026",
                }}
            />
        </AppUserDetailContext.Provider>,
    );

    await user.click(screen.getByRole("button", { name: /查看用户详情/ }));

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

test("app user detail provider fetches detail and renders current pretty id", async () => {
    const user = userEvent.setup();
    vi.stubGlobal(
        "fetch",
        vi.fn(
            async () =>
                new Response(
                    JSON.stringify({
                        code: 0,
                        data: {
                            display_user_id: "123456",
                            default_display_user_id: "123456",
                            pretty_display_user_id: "VIP2026",
                            pretty_id: "pretty-2026",
                            status: "active",
                            user_id: "10001",
                            username: "tester",
                        },
                    }),
                ),
        ),
    );

    render(
        <ToastProvider>
            <MemoryRouter>
                <AppUserDetailProvider>
                    <AdminUserIdentity openInAppUserDetail user={{ displayUserId: "123456", userId: "10001" }} />
                </AppUserDetailProvider>
            </MemoryRouter>
        </ToastProvider>,
    );

    await user.click(screen.getByRole("button", { name: /查看用户详情/ }));

    expect((await screen.findAllByText("VIP2026")).length).toBeGreaterThan(0);
    expect(screen.getAllByText("pretty-2026").length).toBeGreaterThan(0);
    expect(String(vi.mocked(fetch).mock.calls[0][0])).toContain("/api/v1/app/users/10001");
});
