import React from "react";
import "@testing-library/jest-dom/extend-expect";
import { fireEvent, render, RenderResult } from "@testing-library/react";
import { Button, Modal, ModalBody, ModalFooter, ModalHeader, ModalTitle } from "../../";

let elementRender: RenderResult;
let onClose: jest.Mock;
let onSubmit: jest.Mock;

beforeEach(() => {
  onClose = jest.fn();
  onSubmit = jest.fn();
  elementRender = render(
    <Modal onClose={onClose} className="className">
      <ModalHeader onClose={onClose}>
        <ModalTitle>Modal title</ModalTitle>
      </ModalHeader>
      <ModalBody>
        <p>Modal body text goes here.</p>
      </ModalBody>
      <ModalFooter>
        <Button onClick={onClose} variant="light">
          Close
        </Button>
        <Button onClick={onSubmit}>Save changes</Button>
      </ModalFooter>
    </Modal>
  );
});

afterEach(() => {
  onClose.mockReset();
  onSubmit.mockReset();
  elementRender.unmount();
});

test("Should show Modal and pass custom className", () => {
  const { queryByTestId } = elementRender;
  expect(queryByTestId("honey-ui-modal")).toBeTruthy();
  expect(queryByTestId("honey-ui-modal")).toHaveClass("modal d-block fade show className");
});

test("Should able to close Modal on outer click", () => {
  const { queryByTestId } = elementRender;

  fireEvent.click(queryByTestId("honey-ui-modal-overlay"));
  expect(onClose).toHaveBeenCalled();
});

test("Should able to close Modal on EscapeKey", () => {
  fireEvent.keyUp(document, { key: "Escape" });
  expect(onClose).toHaveBeenCalled();
});

test("Should able to close when click on [x]", () => {
  const { queryByTestId } = elementRender;

  fireEvent.click(queryByTestId("honey-ui-modal-header-close-button"));
  expect(onClose).toHaveBeenCalled();
});

test("Should able to use Modal in relative mode", () => {
  const { queryByTestId } = render(
    <Modal onClose={onClose} className="className" isRelative data-testid="relative-honey-ui-modal">
      <ModalHeader onClose={onClose}>
        <ModalTitle>Modal title</ModalTitle>
      </ModalHeader>
      <ModalBody>
        <p>Modal body text goes here.</p>
      </ModalBody>
      <ModalFooter>
        <Button onClick={onClose} variant="light">
          Close
        </Button>
        <Button onClick={onSubmit}>Save changes</Button>
      </ModalFooter>
    </Modal>
  );

  expect(queryByTestId("relative-honey-ui-modal")).toHaveClass("position-relative");
  expect(queryByTestId("relative-honey-ui-modal-backdrop")).toHaveClass(
    "position-absolute h-100 w-100"
  );
});

test("Should able `Vertically centered` Modal dialog", () => {
  const { queryByTestId } = render(
    <Modal
      onClose={onClose}
      className="className"
      isCentered
      data-testid="centered-honey-ui-modal"
    />
  );

  expect(queryByTestId("centered-honey-ui-modal-dialog")).toHaveClass("modal-dialog-centered");
});
