import React from 'react';

import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';
import renderWithTheme from '../../../testUtils/renderWithTheme';

import Checkbox from '..';

const CheckboxButton = Checkbox.Button;

describe('rendering', () => {
  it('shows text label', () => {
    const { getByText } = renderWithTheme(
      <CheckboxButton value="checkboxButton" text="CheckboxButton Text" />
    );
    expect(getByText('CheckboxButton Text')).toBeInTheDocument();
  });

  it('allows to customize text', () => {
    const { getByText } = renderWithTheme(
      <CheckboxButton
        value="checkboxButton"
        text={<div>Customized text</div>}
      />
    );
    expect(getByText('Customized text')).toBeInTheDocument();
  });
});

describe('interaction', () => {
  it('triggers onChange when clicking on the button', () => {
    const onChange = jest.fn();
    const { getByText } = renderWithTheme(
      <CheckboxButton
        value="checkboxButton"
        text="CheckboxButton Text"
        onChange={(e): void => onChange(e.target.checked)}
      />
    );

    userEvent.click(getByText('CheckboxButton Text'));
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith(true);

    userEvent.click(getByText('CheckboxButton Text'));
    expect(onChange).toHaveBeenCalledTimes(2);
    expect(onChange).toHaveBeenCalledWith(false);
  });

  it('does not trigger onChange when clicking on a disabled button', async () => {
    const onChange = jest.fn();
    const { getByText } = renderWithTheme(
      <CheckboxButton
        value="checkboxButton"
        text="CheckboxButton Text"
        disabled
        onChange={(e): void => onChange(e.target.checked)}
      />
    );

    await waitFor(() => {
      expect(() =>
        userEvent.click(getByText('CheckboxButton Text'))
      ).toThrowError(
        'unable to click element as it has or inherits pointer-events set to "none".'
      );
    });
    expect(onChange).not.toHaveBeenCalled();
  });

  it('allows to be controlled', () => {
    const onChange = jest.fn();
    const { getByText } = renderWithTheme(
      <CheckboxButton
        value="checkboxButton"
        text="CheckboxButton Text"
        checked={false}
        onChange={(e): void => onChange(e.target.checked)}
      />
    );

    userEvent.click(getByText('CheckboxButton Text'));
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith(true);
  });
});
