import React from 'react';
import { fireEvent, screen } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as runControllerMutations from 'src/apollo/mutations/run-controller';
import {
    RunControllerFormModal,
    RunControllerFormModalPropsTypes,
} from 'src/components/run-controllers-list/run-controller-form-modal';
import { CONTRACT_TYPES } from 'src/constants';

describe('<RunControllerFormPopup>', () => {
    const render = (props: RunControllerFormModalPropsTypes) =>
        renderInAppContext(<RunControllerFormModal {...props} />);

    const defaultProps: RunControllerFormModalPropsTypes = {
        isRunControllerFormModalOpen: true,
        onRequestCloseModal: jest.fn(),
    };
    const saveRunController = jest.fn().mockResolvedValue({});

    afterEach(jest.restoreAllMocks);

    beforeEach(() => {
        jest.spyOn(
            runControllerMutations,
            'useCreateRunController'
        ).mockReturnValue(saveRunController);
    });

    it('renders run controller form', () => {
        render(defaultProps);
        expect(screen.getByText('New Run Controller')).toBeDefined();
        expect(screen.getByText('Contract Type')).toBeDefined();
        expect(screen.getByText('Name')).toBeDefined();
        expect(screen.getByText('cancel')).toBeDefined();
        expect(screen.getByText('Create')).toBeDefined();
    });

    it('fires the onRequestCloseModal when the cancel button is clicked', () => {
        render(defaultProps);
        const cancelButton = screen.getByText('cancel');
        fireEvent.click(cancelButton);

        expect(defaultProps.onRequestCloseModal).toHaveBeenCalled();
    });

    it('displays error messages when present', () => {
        render(defaultProps);

        const createButton = screen.getByText('Create');
        fireEvent.click(createButton);
        expect(screen.getByText('Name cannot be blank')).toBeDefined();
    });

    it('fires the saveRunController when the create button is clicked', () => {
        render(defaultProps);

        const newRunControllerName = 'Super Awesome Run Controller';
        const createButton = screen.getByText('Create');

        const nameField = screen.getByTestId('run-controller-name');
        fireEvent.change(nameField, {
            target: { value: 'Super Awesome Run Controller' },
        });
        fireEvent.click(createButton);
        expect(saveRunController).toHaveBeenCalledWith({
            variables: {
                contractType: CONTRACT_TYPES.DISTRIBUTION,
                runControllerName: newRunControllerName,
            },
        });
    });
});
