import { shallow } from 'enzyme';
import * as React from 'react';
import sinon from 'sinon';

import { mockUseState } from '~/test/mocks';
import { assert } from '~/test/utils';

import { TextField } from './text-field';

describe('TextField', () => {
  it('simulates onPressBackButton events', () => {
    const onChangeText = sinon.spy();
    const wrapper = shallow(
      <TextField
        placeholderTx="storybook.loremIpsum"
        testID="text-input"
        onChangeText={onChangeText}
      />,
    );

    wrapper.find({ testID: 'text-input' }).prop('onChangeText')('lorem-ipsum');

    assert.calledOnceWithExactly(onChangeText, 'lorem-ipsum');
  });

  it('displays an email text field', () => {
    const wrapper = shallow(
      <TextField placeholderTx="storybook.loremIpsum" testID="text-input" textType="email" />,
    );
    expect(wrapper.find({ testID: 'text-input' }).prop('keyboardType')).toBe('email-address');
    expect(wrapper.find({ testID: 'text-input' }).prop('textContentType')).toBe('emailAddress');
  });

  it('can handle focus event', function () {
    const useStateStub = mockUseState();
    const setFocus = sinon.spy();
    const focusHandler = sinon.spy();

    useStateStub.onCall(0).callsFake((init) => [init, setFocus]);

    const wrapper = shallow(
      <TextField placeholderTx="storybook.loremIpsum" testID="text-input" onFocus={focusHandler} />,
    );

    wrapper.find({ testID: 'text-input' }).prop('onFocus')();

    assert.calledOnceWithExactly(setFocus, true);
    assert.calledOnce(focusHandler);

    useStateStub.restore();
  });

  it('can handle blur event', function () {
    const useStateStub = mockUseState();
    const setFocus = sinon.spy();
    const blurHandler = sinon.spy();

    useStateStub.onCall(0).callsFake((init) => [init, setFocus]);

    const wrapper = shallow(
      <TextField placeholderTx="storybook.loremIpsum" testID="text-input" onBlur={blurHandler} />,
    );

    wrapper.find({ testID: 'text-input' }).prop('onBlur')();

    assert.calledOnceWithExactly(setFocus, false);
    assert.calledOnce(blurHandler);

    useStateStub.restore();
  });
});
