import { render, fireEvent, screen } from '../test-utils';

import CheckboxOption from '.';

describe('Checkbox option', () => {
  const defaultProps = {
    id: 'id',
    name: 'name',
    title: 'Title',
    onChange: jest.fn(),
    'aria-label': 'test-label',
  };

  describe('by default', () => {
    render(<CheckboxOption {...defaultProps} />);
    const checkbox = screen.getByRole('checkbox');
    it('is not checked', () => {
      expect(checkbox).not.toBeChecked();
    });

    it('is not disabled', () => {
      expect(checkbox).toBeEnabled();
    });
  });

  it('has `aria-label` attr', () => {
    render(<CheckboxOption {...defaultProps} />);
    const checkbox = screen.getByLabelText('test-label');
    expect(checkbox).toBeInTheDocument();
  });

  it('is checked when checked prop is true', () => {
    render(<CheckboxOption {...defaultProps} checked />);
    expect(screen.getByRole('checkbox')).toBeChecked();
  });

  it('is disabled when disabled prop is true', () => {
    render(<CheckboxOption {...defaultProps} disabled />);
    expect(screen.getByRole('checkbox')).toBeDisabled();
  });

  describe('onChange', () => {
    it('is called with new checked value when the option is clicked', () => {
      const onChange = jest.fn();
      const { rerender } = render(<CheckboxOption {...defaultProps} onChange={onChange} />);

      const label = screen.getByLabelText('test-label');

      expect(onChange).not.toHaveBeenCalled();
      fireEvent.click(label);
      expect(onChange).toHaveBeenCalledWith(true);

      rerender(<CheckboxOption {...defaultProps} checked onChange={onChange} />);
      fireEvent.click(label);
      expect(onChange).toHaveBeenCalledWith(false);
    });

    it('is not called if the option is disabled', () => {
      const onChange = jest.fn();
      render(<CheckboxOption {...defaultProps} disabled onChange={onChange} />);

      const label = screen.getByLabelText('test-label');

      expect(onChange).not.toHaveBeenCalled();
      fireEvent.click(label);
      expect(onChange).not.toHaveBeenCalled();
    });
  });

  it('renders aligned with container content', () => {
    render(<CheckboxOption {...defaultProps} isContainerAligned />);
    expect(document.querySelector('.np-option__container-aligned')).toBeInTheDocument();
  });
});
