import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import waitForExpect from 'wait-for-expect';
import { Alert } from './Alert';
import 'jest-styled-components';
import { CloseBtn } from '../CloseBtn';

describe('Modal', () => {
   beforeAll(() => {
      (ReactDOM.createPortal as any) = jest.fn((element, node) => {
         return element;
      });
   });

   afterEach(() => {
      (ReactDOM.createPortal as any).mockClear();
   });

   it('snapshot - modal open', () => {
      const tree = renderer.create(<Alert show />).toJSON();
      expect(tree).toMatchSnapshot();
   });

   it('snapshot - modal calose', () => {
      const tree = renderer.create(<Alert show={false} />).toJSON();
      expect(tree).toMatchSnapshot();
   });

   it('loads and displays greeting', async () => {
      const onHide = jest.fn();
      function ComponentExample(): any {
         const [show, setShow] = useState(false);

         return (
            <>
               <button onClick={() => setShow(true)} data-testid="button">
                  button
               </button>
               <Alert
                  show={show}
                  onHide={onHide}
                  // onRequestClose={() => {
                  //    setHide(true);
                  // }}
               >
                  <Alert.Body className="p-4">
                     <span>
                        <CloseBtn onClick={() => setShow(false)} data-testid="close-btn" />
                     </span>
                     <div className="p-4" data-testid="modal-body">
                        Modal Body
                     </div>
                  </Alert.Body>
               </Alert>
            </>
         );
      }

      render(<ComponentExample />);

      // não deve mostrar modal
      expect(screen.queryByText('Modal1')).toBeNull();

      fireEvent.click(screen.getByTestId('button'));
      await waitFor(() => screen.getByText('Modal Body'));

      // mostrar modal
      expect(screen.queryByText('Modal Body')).not.toBeNull();

      // fechar modal
      fireEvent.click(screen.getByTestId('close-btn'));

      // called
      waitForExpect(() => expect(onHide).toHaveBeenCalled());
   });
});
