import * as _ from 'lodash';
import * as React from 'react';
import * as Renderer from 'react-test-renderer';
import { Button, Select } from 'twitch-core-ui';
import { GrantPermissionsModal } from '.';

jest.mock('react-dom', () => ({
  // tslint:disable-next-line:no-any
  createPortal: (node: any) => node,
}));

let mockLoading = false;

jest.mock('dashboard/core/utils/event-stream', () => ({
  useEventTypes: () => {
    return {
      loading: mockLoading,
    };
  },
}));

describe('CreateIAMRoleModal', () => {
  it('renders (loading spinner)', () => {
    mockLoading = true;
    expect(
      Renderer.create(
        <React.Fragment>
          <GrantPermissionsModal
            service={{ id: '123' }}
            onSuccess={_.noop}
          />
        </React.Fragment>,
      ),
    ).toMatchSnapshot();
  });

  it('renders (loaded)', () => {
    mockLoading = false;
    expect(
      Renderer.create(
        <React.Fragment>
          <GrantPermissionsModal
            service={{ id: '123' }}
            onSuccess={_.noop}
          />
        </React.Fragment>,
      ),
    ).toMatchSnapshot();
  });
});

describe('save button', () => {
  const root = Renderer.create(
    <GrantPermissionsModal service={{ id: '123' }} onSuccess={_.noop} />,
  ).root;

  it('is disabled by default', () => {
    const saveButton = root.find(
      (node: Renderer.ReactTestInstance) =>
        node.type === Button && node.props.children === 'Grant',
    );
    expect(saveButton.props.disabled).toBe(true);
  });

  it('is enabled when all fields are filled', () => {
    const arnSelect = root.find(
      (node: Renderer.ReactTestInstance) =>
        node.type === Select && node.props.id === 'arn',
    );
    Renderer.act(() => {
      arnSelect.props.onChange({
        currentTarget: {
          value: 'arn',
        },
      });
    });
    const environmentSelect = root.find(
      (node: Renderer.ReactTestInstance) =>
        node.type === Select && node.props.id === 'environment',
    );
    Renderer.act(() => {
      environmentSelect.props.onChange({
        currentTarget: {
          value: 'production',
        },
      });
    });
    const eventTypeSelect = root.find(
      (node: Renderer.ReactTestInstance) =>
        node.type === Select && node.props.id === 'eventType',
    );
    Renderer.act(() => {
      eventTypeSelect.props.onChange({
        currentTarget: {
          value: 'production',
        },
      });
    });
    const saveButton = root.find(
      (node: Renderer.ReactTestInstance) =>
        node.type === Button && node.props.children === 'Grant',
    );
    expect(saveButton.props.disabled).toBe(false);
  });
});
