import React, { useState } from 'react';
import { cleanup } from '@testing-library/react';
import { render } from '../../../utils/theme-render-wrapper';
import TestUtils from 'react-dom/test-utils';
import { SearchField } from './search-field';

afterEach(cleanup);

const value = 'Hello world';

describe('<SearchField />', () => {
  it(`Should render uncontrolled SearchField and check typing and reset`, () => {
    const handleChangeCallback = jest.fn();
    const { container } = render(<SearchField handleChangeCallback={handleChangeCallback} />);

    const inputEl = container.querySelector('input');
    if (inputEl) {
      inputEl.value = value;
      TestUtils.Simulate.change(inputEl);
    }
    expect(inputEl?.value).toBe(value);

    const buttonEl = container.querySelector('button');
    buttonEl?.click();

    expect(inputEl?.value).toBe('');
    expect(handleChangeCallback).toHaveBeenCalled();
  });

  it(`Should render controlled SearchField and check typing and reset`, () => {
    const Wrapper = () => {
      const [controlledValue, setControlledValue] = useState('');

      const handleClear = () => {
        setControlledValue('');
      };

      return (
        <SearchField
          value={controlledValue}
          onChange={e => setControlledValue(e.target.value)}
          handleClear={handleClear}
        />
      );
    };
    const { container } = render(<Wrapper />);

    const inputEl = container.querySelector('input');
    if (inputEl) {
      inputEl.value = value;
      TestUtils.Simulate.change(inputEl);
    }
    expect(inputEl?.value).toBe(value);

    const buttonEl = container.querySelector('button');
    buttonEl?.click();

    expect(inputEl?.value).toBe('');
  });
});
