// @flow
import React from 'react';
import { act } from 'react-dom/test-utils';
import { useModal } from './use-modal';
import { Modal } from '.';
import { mountWrappedComponent } from '../../../../utils/tests';

describe('use-modal hook', () => {
  const TestComponent = () => {
    const { showModal, onModalClose, onModalToggle } = useModal();

    return (
      <>
        <button type="button" onClick={onModalToggle} id="open-button">
          open modal
        </button>
        <Modal show={showModal} onClose={onModalClose}>
          <div>child</div>
        </Modal>
      </>
    );
  };

  const toggleModal = component => {
    component.find('#open-button').simulate('click');
    return component.update();
  };

  it('defaults to a hidden modal', () => {
    const component = mountWrappedComponent(<TestComponent />);

    expect(component.find('Modal').prop('show')).toEqual(false);
  });

  it('sets show to the passed in initialShowModal', () => {
    const TestComponentWithInitial = () => {
      const { showModal, onModalClose, onModalToggle } = useModal(true);

      return (
        <>
          <button type="button" onClick={onModalToggle} id="open-button">
            open modal
          </button>
          <Modal show={showModal} onClose={onModalClose}>
            <div>child</div>
          </Modal>
        </>
      );
    };

    const component = mountWrappedComponent(<TestComponentWithInitial />);

    expect(component.find('Modal').prop('show')).toEqual(true);
  });

  it('toggles showModal state when firing onModalToggle', () => {
    let component = mountWrappedComponent(<TestComponent />);

    component = toggleModal(component);

    expect(component.find('Modal').prop('show')).toEqual(true);

    component = toggleModal(component);

    expect(component.find('Modal').prop('show')).toEqual(false);
  });

  it('closes the modal when using onModalClose', () => {
    let component = mountWrappedComponent(<TestComponent />);

    component = toggleModal(component);

    act(() => {
      component.find('Modal').prop('onClose')();
    });
    component = component.update();

    expect(component.find('Modal').prop('show')).toEqual(false);
  });
});
