import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type React from "react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createI18nMock } from "../../../test/i18nMock";
import { TenantFineGrainedPermissionsPage } from "./TenantFineGrainedPermissionsPage";

const fetchUsersMock = vi.hoisted(() => vi.fn());
const bulkUpdateUsersMock = vi.hoisted(() => vi.fn());

vi.mock("../../../lib/i18n", () => createI18nMock());

vi.mock("../../../lib/adminApi", () => ({
  addSystemRelation: vi.fn(async () => undefined),
  addTenantRelation: vi.fn(async () => undefined),
  bulkUpdateUsers: bulkUpdateUsersMock,
  fetchAllTenants: vi.fn(async () => ({ items: [], total: 0 })),
  fetchMe: vi.fn(async () => ({
    id: "current-admin",
    name: "Current Admin",
    email: "current@example.com",
    role: "super_admin",
  })),
  fetchSystemRelations: vi.fn(async () => []),
  fetchTenantRelations: vi.fn(async () => []),
  fetchUsers: fetchUsersMock,
  removeSystemRelation: vi.fn(async () => undefined),
  removeTenantRelation: vi.fn(async () => undefined),
}));

function renderWithProviders(ui: React.ReactElement) {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
      mutations: { retry: false },
    },
  });

  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter initialEntries={["/permissions-direct"]}>{ui}</MemoryRouter>
    </QueryClientProvider>,
  );
}

describe("TenantFineGrainedPermissionsPage Super Admin role tab", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    bulkUpdateUsersMock.mockResolvedValue({ results: [] });
    fetchUsersMock.mockResolvedValue({
      items: [
        {
          id: "current-admin",
          name: "Current Admin",
          email: "current@example.com",
          role: "super_admin",
          status: "active",
          createdAt: "2026-06-17T00:00:00Z",
          updatedAt: "2026-06-17T00:00:00Z",
        },
        {
          id: "bootstrap-admin",
          name: "Bootstrap Admin",
          email: "env-admin@example.com",
          role: "super_admin",
          status: "active",
          metadata: { bootstrapSuperAdmin: true },
          createdAt: "2026-06-17T00:00:00Z",
          updatedAt: "2026-06-17T00:00:00Z",
        },
        {
          id: "delegated-admin",
          name: "Delegated Admin",
          email: "delegated@example.com",
          role: "super_admin",
          status: "active",
          createdAt: "2026-06-17T00:00:00Z",
          updatedAt: "2026-06-17T00:00:00Z",
        },
        {
          id: "regular-user",
          name: "Regular User",
          email: "regular@example.com",
          phone: "010-0000-0001",
          role: "user",
          status: "active",
          createdAt: "2026-06-17T00:00:00Z",
          updatedAt: "2026-06-17T00:00:00Z",
        },
      ],
      total: 4,
      limit: 1000,
      offset: 0,
    });
  });

  it("shows revocable super admin users even when they have no direct system relations", async () => {
    renderWithProviders(
      <Routes>
        <Route
          path="/permissions-direct"
          element={<TenantFineGrainedPermissionsPage />}
        />
      </Routes>,
    );

    fireEvent.click(
      await screen.findByRole("tab", { name: "Super Admin 역할" }),
    );

    expect(await screen.findByText("Delegated Admin")).toBeInTheDocument();
    expect(screen.getByText("delegated@example.com")).toBeInTheDocument();
    expect(screen.queryByText("Current Admin")).not.toBeInTheDocument();
    expect(screen.queryByText("Bootstrap Admin")).not.toBeInTheDocument();
    expect(screen.queryByText("Regular User")).not.toBeInTheDocument();

    fireEvent.click(
      screen.getByTestId("super-admin-role-user-delegated-admin"),
    );
    fireEvent.click(screen.getByRole("button", { name: "Super Admin 회수" }));

    await waitFor(() =>
      expect(bulkUpdateUsersMock).toHaveBeenCalledWith({
        userIds: ["delegated-admin"],
        role: "user",
      }),
    );
  });

  it("searches regular users and grants the Super Admin role from the target queue", async () => {
    renderWithProviders(
      <Routes>
        <Route
          path="/permissions-direct"
          element={<TenantFineGrainedPermissionsPage />}
        />
      </Routes>,
    );

    fireEvent.click(
      await screen.findByRole("tab", { name: "Super Admin 역할" }),
    );

    fireEvent.change(
      await screen.findByPlaceholderText("UUID, 이름, 이메일, 전화번호 검색"),
      { target: { value: "010-0000-0001" } },
    );
    fireEvent.click(screen.getByRole("button", { name: "부여 대상 추가" }));

    expect(
      screen.getByTestId("super-admin-grant-target-regular-user"),
    ).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: "Super Admin 부여" }));

    await waitFor(() =>
      expect(bulkUpdateUsersMock).toHaveBeenCalledWith({
        userIds: ["regular-user"],
        role: "super_admin",
      }),
    );
  });
});
