import { render, screen, mockMatchMedia } from '../test-utils';
import { userEvent } from '@testing-library/user-event';
import RadioGroup from '.';
import AvatarView from '../avatarView';
import { Field } from '../field/Field';

describe('RadioGroup', () => {
  const handleChange = jest.fn();
  const avatar = <AvatarView profileName="High Definition" />;
  mockMatchMedia();

  const RADIOS = [
    {
      id: 'id-test-0',
      value: 'value-test0',
      label: 'Radio1',
      secondary: 'secondary',
      disabled: true,
      avatar,
    },
    {
      id: 'id-test-1',
      value: 'value-test1',
      label: 'Radio2',
      secondary: 'secondary',
      disabled: false,
    },
    {
      id: 'id-test-2',
      value: 'value-test2',
      label: 'Radio3',
      secondary: 'secondary',
      disabled: false,
    },
  ];
  it('has accessible role', () => {
    render(
      <RadioGroup
        name="currency"
        radios={[{ label: 'USD' }, { label: 'EUR' }]}
        onChange={() => {}}
      />,
    );
    expect(screen.getByRole('radiogroup')).toBeInTheDocument();
  });

  it('supports `Field` for labeling', () => {
    render(
      <Field label="Currency">
        <RadioGroup
          name="currency"
          radios={[{ label: 'USD' }, { label: 'EUR' }]}
          onChange={() => {}}
        />
      </Field>,
    );
    expect(screen.getByRole('radiogroup')).toHaveAccessibleName(/^Currency/);
  });

  it('renders nothing if no radios are provided', () => {
    render(<RadioGroup name="radio-group" radios={[]} onChange={handleChange} />);
    expect(screen.queryByRole('radiogroup')).not.toBeInTheDocument();
  });

  it('renders radio options', () => {
    render(<RadioGroup name="radio-group" radios={RADIOS} onChange={handleChange} />);
    expect(screen.getAllByRole('radio')).toHaveLength(RADIOS.length);
    const firstRadio = screen.getByRole('radio', { name: /Radio1/i });
    expect(firstRadio).toBeDisabled();
  });

  it('checks the specified radio value', () => {
    render(
      <RadioGroup
        name="radio-group"
        radios={RADIOS}
        selectedValue="value-test2"
        onChange={handleChange}
      />,
    );
    const checkedRadio = screen.getByRole('radio', { name: /Radio3/i });
    expect(checkedRadio).toBeChecked();
  });

  it('calls onChange with the selected value', async () => {
    render(<RadioGroup name="radio-group" radios={RADIOS} onChange={handleChange} />);
    const thirdRadio = screen.getByRole('radio', { name: /Radio3/i });
    await userEvent.click(thirdRadio);
    expect(handleChange).toHaveBeenCalledWith('value-test2');
  });
});
