import * as React from 'react';
import {shallow, ShallowWrapper} from 'enzyme';
import {createMockEnvironment, MockPayloadGenerator} from 'relay-test-utils';
import {QueryRenderer, graphql} from 'react-relay';
import * as ReactTestRenderer from 'react-test-renderer';

import FragmentedPokemonShow, {
  PokemonShow,
  Props,
} from 'components/pages/pokemon/Show';
import {Show_pokemon as ShowPokemonDataType} from 'components/pages/pokemon/__generated__/Show_pokemon.graphql';

const pokemon: ShowPokemonDataType = {
  id: '1',
  iid: 'x1',
  nickname: 'Bulbasaur',
  pokedexNumber: 1,
  ' $refType': '' as any,
};

const defaultProps = {
  pokemon: pokemon,
};

function setup(props = defaultProps): ShallowWrapper {
  return shallow(<PokemonShow {...props} />);
}

describe('<PokemonShow />', () => {
  it('displays a pokemon', () => {
    const wrapper = setup();
    expect(wrapper).toMatchSnapshot();
  });

  it('requests data from a GraphQL fragment', () => {
    const environment = createMockEnvironment();
    const mockId = 'mock-id-1';

    const TestRenderer = (): JSX.Element => (
      <QueryRenderer
        environment={environment}
        query={graphql`
          query Show_pokemonSuccessQuery($mockId: ID!) @relay_test_operation {
            pokemon: node(id: $mockId) {
              ...Show_pokemon
            }
          }
        `}
        render={args => {
          const {error, props} = args as {error: Error; props: Props};
          if (props) {
            // Prevent TS Compiler from complaining about unsupplied props
            const Component = FragmentedPokemonShow as any;

            // eslint-disable-next-line react/prop-types
            return <Component pokemon={props.pokemon} />;
          } else if (error) {
            return error.message;
          }
          return 'Loading...';
        }}
        variables={{mockId}}
      />
    );

    environment.mock.queueOperationResolver(operation =>
      MockPayloadGenerator.generate(operation, {
        Pokemon: () => ({
          id: mockId,
          iid: '1',
          nickname: 'Bulba',
          pokedexNumber: 3,
        }),
      })
    );

    const renderer = ReactTestRenderer.create(<TestRenderer />);
    expect(renderer).toMatchSnapshot();
  });
});
