import React from 'react';
import { fireEvent } from '@testing-library/react';

import renderWithTheme from '../../../testUtils/renderWithTheme';

import Input from '..';
import Typography from '../../Typography';

const { TextArea } = Input;

describe('rendering', () => {
  it('renders textarea', () => {
    const { getAllByText } = renderWithTheme(
      <TextArea value="Email" onChange={jest.fn()} autoResize />
    );

    expect(getAllByText('Email')).toHaveLength(2);
  });
});

describe('interaction', () => {
  it('works as uncontrolled component', () => {
    const { getByLabelText } = renderWithTheme(
      <Typography.Text tagName="label">
        Email
        <TextArea />
      </Typography.Text>
    );
    expect((getByLabelText('Email') as HTMLInputElement).value).toEqual('');
    fireEvent.change(getByLabelText('Email'), {
      target: { value: 'new value' },
    });
    expect((getByLabelText('Email') as HTMLInputElement).value).toEqual(
      'new value'
    );
  });

  it('works as controlled component', () => {
    const onChange = jest.fn();
    const { getByLabelText } = renderWithTheme(
      <Typography.Text tagName="label">
        Email
        <TextArea
          value="fixed"
          onChange={(e): void => onChange(e.target.value)}
          autoResize={false}
        />
      </Typography.Text>
    );
    expect((getByLabelText('Email') as HTMLInputElement).value).toEqual(
      'fixed'
    );
    fireEvent.change(getByLabelText('Email'), {
      target: { value: 'new value' },
    });
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith('new value');
    expect((getByLabelText('Email') as HTMLInputElement).value).toEqual(
      'fixed'
    );
  });

  it('can get auto focus', () => {
    const onFocus = jest.fn();
    renderWithTheme(<TextArea onFocus={onFocus} autoFocus />);
    expect(onFocus).toHaveBeenCalledTimes(1);
  });
});
