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

it('snapshot - default', () => {
   const tree = renderer
      .create(
         <>
            <Form onSubmit={() => {}}>
               <InputCounter name="default" />
            </Form>
         </>,
      )
      .toJSON();
   expect(tree).toMatchSnapshot();
});

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

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

      return (
         <>
            <Form onSubmit={() => {}} ref={formRef}>
               <InputCounter name="default" />
            </Form>
         </>
      );
   }

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

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

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

it('incrementar número', () => {
   const onSubmit = jest.fn();

   function Component(): any {
      return (
         <Form onSubmit={(data) => onSubmit(data)}>
            <InputCounter name="default" />
            <button type="submit" data-testid="submit">
               Submit
            </button>
         </Form>
      );
   }

   render(<Component />);

   // Definir data
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('submit'));

   expect(onSubmit).toHaveBeenCalled();
   expect(onSubmit).toHaveBeenCalledWith({
      default: '4',
   });
});

it('decrementar número', () => {
   const onSubmit = jest.fn();

   function Component(): any {
      return (
         <Form onSubmit={(data) => onSubmit(data)}>
            <InputCounter name="default" />
            <button type="submit" data-testid="submit">
               Submit
            </button>
         </Form>
      );
   }

   render(<Component />);

   // Definir data
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('add-number'));
   fireEvent.click(screen.getByTestId('sub-number'));
   fireEvent.click(screen.getByTestId('sub-number'));
   fireEvent.click(screen.getByTestId('submit'));

   expect(onSubmit).toHaveBeenCalled();
   expect(onSubmit).toHaveBeenCalledWith({
      default: '2',
   });
});
