import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MockedProvider } from "@apollo/client/testing";
import { MemoryRouter } from "react-router-dom";
import Main from "./Main";
import { SnackbarProvider } from "notistack";
import { JwtPayload } from "../jwt/jwt";
import { queryAllMenuIconButtons } from "../integration-tests/test-helper";

function renderMainPage(jwt: JwtPayload) {
  render(
    <MockedProvider>
      <MemoryRouter>
        <SnackbarProvider>
          <Main userRole={jwt.role} loggedInUserRowId={jwt.person_row_id} />
        </SnackbarProvider>
      </MemoryRouter>
    </MockedProvider>
  );
}

const baseJwt: JwtPayload = {
  aud: "postgraphile",
  exp: 0,
  iat: 0,
  iss: "postgraphile",
  role: "kandimat_person",
  person_row_id: 3,
};

describe("As an editor, the main page", () => {
  const jwt: JwtPayload = {
    ...baseJwt,
    role: "kandimat_editor",
    person_row_id: 1,
  };

  test("displays the editor's home page", () => {
    renderMainPage(jwt);

    // it renders question and category lists
    const questionListHeadline = screen.queryAllByText(/Fragen/);
    const categoryListHeadline = screen.queryByText(/Kategorien/);
    expect(questionListHeadline.length).toBeGreaterThan(0);
    expect(categoryListHeadline).not.toBeNull();
  });

  test("has a menu with two entries", async () => {
    renderMainPage(jwt);

    const menuButton = queryAllMenuIconButtons();
    expect(menuButton).toHaveLength(1);
    fireEvent.click(menuButton[0]);

    // renders the two menu entries for an editor
    await waitFor(() => {
      expect(
        screen.queryAllByRole("button", { name: /fragen|benutzer/i })
      ).toHaveLength(2);
    });
  });
});

describe("As a candidate, the main page", () => {
  test("displays the candidate's home page ", () => {
    const jwt: JwtPayload = {
      ...baseJwt,
      role: "kandimat_candidate",
      person_row_id: 2,
    };
    renderMainPage(jwt);

    const questionListHeadline = screen.queryAllByText(/Fragen/);
    const categoryListHeadline = screen.queryByText(/Kategorien/);
    expect(questionListHeadline.length).toBeGreaterThan(0);
    expect(categoryListHeadline).toBeNull();
  });
});

describe("As a simple user, the main page", () => {
  test("displays the user's home page.", () => {
    const jwt: JwtPayload = {
      ...baseJwt,
      role: "kandimat_person",
      person_row_id: 3,
    };
    renderMainPage(jwt);

    const placeholder = screen.queryByText(/nichts zu sehen/);
    expect(placeholder).not.toBeNull();
  });
});
