import React, { useState } from 'react';

import { fireEvent } from '@testing-library/react';

import Modal from '../index';
import renderWithTheme from '../../../testUtils/renderWithTheme';

window.scrollTo = jest.fn();

describe('rendering', () => {
  it('allows to customise modal contents using sub components', () => {
    const { getByText, getByTestId } = renderWithTheme(
      <Modal open>
        <Modal.Header>Customised header</Modal.Header>
        <Modal.Body>Customised body</Modal.Body>
        <Modal.Footer>Customised footer</Modal.Footer>
        <Modal.CloseButton data-test-id="customised-close-button" />
      </Modal>
    );
    expect(getByText('Customised header')).toBeInTheDocument();
    expect(getByText('Customised body')).toBeInTheDocument();
    expect(getByText('Customised footer')).toBeInTheDocument();
    expect(getByText('Customised footer')).toBeInTheDocument();
    expect(getByTestId('customised-close-button')).toBeInTheDocument();
  });
});

describe('a modal open another', () => {
  it('lock scroll on body correctly', () => {
    const Modals = () => {
      const [open1, setOpen1] = useState(true);
      const [open2, setOpen2] = useState(true);

      return (
        <>
          <button type="button" onClick={() => setOpen1(true)}>
            Open first Modal
          </button>
          <Modal
            title="A title"
            body={
              <button type="button" onClick={() => setOpen2(true)}>
                Open second Modal
              </button>
            }
            open={open1}
            footer={
              <button type="button" onClick={() => setOpen1(false)}>
                Close first Modal
              </button>
            }
          />
          <Modal.PopUp
            title="A title"
            body="A body"
            open={open2}
            footer={
              <button type="button" onClick={() => setOpen2(false)}>
                Close second Modal
              </button>
            }
          />
        </>
      );
    };
    const { getByText } = renderWithTheme(<Modals />);

    fireEvent.click(getByText('Open first Modal'));
    expect(document.body.style.position).toEqual('fixed');

    fireEvent.click(getByText('Open second Modal'));
    expect(document.body.style.position).toEqual('fixed');

    fireEvent.click(getByText('Close second Modal'));
    expect(document.body.style.position).toEqual('fixed');

    fireEvent.click(getByText('Close first Modal'));
    expect(document.body.style.position).toEqual('');
  });
});
