import React, { useEffect, useRef } from 'react';
import renderer from 'react-test-renderer';
import { render, fireEvent, screen } from '@testing-library/react';
import { FormHandles } from '@unform/core';
import { Form } from '@unform/web';
import 'jest-styled-components';
import { Textarea } from './Textarea';

it('snapshot - default', () => {
   const tree = renderer
      .create(
         <>
            <Form onSubmit={() => {}}>
               <Textarea name="default" />
            </Form>
         </>,
         {
            createNodeMock(element: React.ReactElement): any {
               return document.createElement('textarea');
            },
         },
      )
      .toJSON();
   expect(tree).toMatchSnapshot();
});

it('snapshot - title', () => {
   const tree = renderer
      .create(
         <>
            <Form onSubmit={() => {}}>
               <Textarea name="default" title="Full Name" />
            </Form>
         </>,
         {
            createNodeMock(element: React.ReactElement): any {
               return document.createElement('textarea');
            },
         },
      )
      .toJSON();
   expect(tree).toMatchSnapshot();
});

it('snapshot - with error', () => {
   function Component(): any {
      const formRef = useRef<FormHandles>();

      useEffect(() => {
         formRef.current.setFieldError('default', 'Field Invalid');
      }, []);

      return (
         <>
            <Form onSubmit={() => {}} initialData={{ default: 'default' }} ref={formRef}>
               <Textarea name="default" />
            </Form>
         </>
      );
   }

   const { container } = render(<Component />);

   expect(screen.getByTestId('input-error')).not.toBeUndefined();

   expect(container.firstChild).toMatchSnapshot();
});

it('unform - onSubmit', () => {
   const onSubmit = jest.fn();

   function Component() {
      const formRef = useRef<FormHandles>();

      return (
         <Form ref={formRef} onSubmit={(v) => onSubmit(v)} initialData={{ default: ' email @simple. com. br' }}>
            <Textarea name="default" />
            <button
               data-testid="submit"
               title="submit"
               type="button"
               onClick={() => {
                  formRef.current.submitForm();
               }}
            />
         </Form>
      );
   }
   render(<Component />);

   fireEvent.click(screen.getByTestId('submit'));

   expect(onSubmit).toHaveBeenCalled();
   expect(onSubmit).toHaveBeenCalledWith({ default: ' email @simple. com. br' });
});
