import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { MdClose } from '@react-icons/all-files/md/MdClose';

import Modal from '.';
import ModalProvider from './modalContext';
import ModalContent from './modal-content';

const setUp = () => {
  React.useContext = ModalProvider;
  const { container, getAllByText } = render(
    <ModalProvider>
      <Modal content="Modal opened">
        <p>Click me</p>
      </Modal>
      <ModalContent closeIcon={<MdClose />} overlay />
    </ModalProvider>
  );
  return { container, getAllByText };
};

describe('Modal Component', () => {
  test('render with props', () => {
    const { container, getAllByText } = setUp();

    expect(container).toBeTruthy();
    expect(container.querySelector('.modalOverlay')).toBeTruthy();
    expect(container.querySelector('svg')).toBeTruthy();
    expect(container.querySelector('.activeModal')).toBeFalsy();
    expect(getAllByText('Click me'));
  });

  // Toggle effect
  test('toggle modal', () => {
    const { container, getAllByText } = setUp();
    const toggleBtn = container.querySelector('p');

    fireEvent.click(toggleBtn);
    expect(container.querySelector('.activeModal')).toBeTruthy();
    expect(getAllByText('Modal opened')).toBeTruthy();

    fireEvent.click(toggleBtn);
    expect(container.querySelector('.activeModal')).toBeFalsy();
  });

  // Close effect
  test('close modal', () => {
    const { container } = setUp();
    const toggleBtn = container.querySelector('p');
    const closeIcon = container.querySelector('svg');

    fireEvent.click(toggleBtn);
    expect(container.querySelector('.activeModal')).toBeTruthy();

    fireEvent.click(closeIcon);
    expect(container.querySelector('.activeModal')).toBeFalsy();
  });
});
afterEach(() => {
  cleanup();
});
