import * as redux from "react-redux";
import store from "../../store";
import { Router } from "react-router-dom";
import { render, screen, fireEvent } from "@testing-library/react";
import history from "../../store/utils/history";
import ConfirmDialog from "../../components/MUI/ConfirmDialog";
import mediaQuery from "css-mediaquery";

function createMatchMedia(width) {
  return (query) => ({
    matches: mediaQuery.match(query, { width }),
    addListener: () => {},
    removeListener: () => {},
  });
}

const onConfirm = jest.fn();
const onClose = jest.fn();

describe("ConfirmDialog render tests", () => {
  var props = {
    title: "title",
    subtitle: "subtitle",
    imageSrc: "path",
    content: "content",
    onConfirm: onConfirm,
    onClose: onClose,
    open: true,
    maxWidth: "lg",
    fullWidth: false,
    responsive: true,
  };
  const cont = (
    <redux.Provider store={store}>
      <Router history={history}>
        <ConfirmDialog {...props} />
      </Router>
    </redux.Provider>
  );

  beforeEach(() => {
    // theme.breakpoints.down("md") will be true if width of screen is less than 900px
    window.matchMedia = createMatchMedia(899);
  });

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

  it("Should render", () => {
    render(cont);
    expect(screen.getByTestId("alert-container")).toBeDefined();
  });

  it("Should render full-screen elements because fullScreen is true", () => {
    render(cont);
    expect(screen.getAllByTestId("full-screen-elem").length).toBe(2);
  });

  it("Should not render not-full-screen elements because fullScreen is true", () => {
    render(cont);
    expect(screen.queryByTestId("not-full-screen-elem")).toBeNull();
  });

  it("Should render content", () => {
    render(cont);
    expect(screen.getByTestId("modal-content")).toBeDefined();
  });

  it("Should not render button because fullScreen is true", () => {
    render(cont);
    expect(screen.queryByTestId("not-full-screen-btn")).toBeNull();
  });

  it("Should render confirm and and x-button", () => {
    render(cont);
    expect(screen.getAllByTestId("btn-testid").length).toBe(2);
  });

  it("Should call onConfirm function once after clicking confirm button", () => {
    render(cont);
    fireEvent.click(screen.getAllByTestId("btn-testid")[1]);
    expect(onConfirm.mock.calls).toHaveLength(1);
  });

  it("Should call onClose function once after clicking Cancel button", () => {
    render(cont);
    fireEvent.click(screen.getAllByTestId("btn-testid")[0]);
    expect(onClose.mock.calls).toHaveLength(1);
  });
});
