import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import * as redux from "react-redux";
import AdDetailsPage from "../../pages/AdsPage/AdDetailsPage";
import store from "../../store";
import { mockState } from "../../mockState";
import { Router } from "react-router-dom";
import history from "../../store/utils/history";
import ColorModeProvider from "../../context/ColorModeContext";

describe("AdDetailsPage render tests", () => {
  var props = {
    history: {
      replace: jest.fn(),

      push: jest.fn(),

      location: {
        pathname: "/ads/1",
      },
    },
  };

  const cont = (
    <redux.Provider store={store}>
      <Router history={history}>
        <ColorModeProvider>
          <AdDetailsPage {...props} />
        </ColorModeProvider>
      </Router>
    </redux.Provider>
  );

  let spyOnUseSelector;

  beforeEach(() => {
    spyOnUseSelector = jest.spyOn(redux, "useSelector");
    spyOnUseSelector.mockReturnValue(mockState.ads.ads[0]);
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it("Should render AdDetailsPage", () => {
    render(cont);
    expect(screen.getByTestId("job-details-page")).toBeDefined();
  });

  it("Should render modal when click archive ad button", () => {
    const { container } = render(cont);

    fireEvent.click(container.getElementsByClassName("archive-job-button")[0]);

    expect(screen.getByTestId("alert-container")).toBeDefined();
  });

  it("Should render ads page when confirm archive ad modal", async () => {
    const { container } = render(cont);

    waitFor(() => {
      fireEvent.click(container.getElementsByClassName("archive-job-button")[0]);

      fireEvent.click(container.getElementsByClassName("dialog-btn")[1]);

      waitFor(() => expect(props.history.push).toHaveBeenCalledWith('/jobs'));
    });
  });

  it("Should render apply for ad button", () => {
    const { container } = render(cont);
    expect(
      container.getElementsByClassName("apply-for-job-button")[0]
    ).toBeDefined();
  });

  it("Should render apply for ad modal after click button", () => {
    const { container } = render(cont);

    fireEvent.click(container.getElementsByClassName("apply-for-job-button")[0]);

    const a = screen.getByTestId("custom-modal-test-id");

    expect(screen.getByTestId("custom-modal-test-id")).toBeDefined();
  });

  it("Should render go back button", () => {
    const { container } = render(cont);
    expect(
      container.getElementsByClassName("job-details-buttons-link")[0]
    ).toBeDefined();
  });

  it("Should go back when click button", async () => {
    const { container } = render(cont);

    fireEvent.click(
      container.getElementsByClassName("job-details-buttons-link")[0]
    );

    const arg = { pathname: "/jobs" };

    waitFor(() => expect(props.history.push).toHaveBeenCalledWith(arg));
  });
});
