import React from 'react';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as contractFlowthroughMutations from 'src/apollo/mutations/contract-flowthrough';
import { deleteContractFlowthroughMessage } from 'src/apollo/type-constants/contract-flowthrough';
import {
    DeleteContractFlowthroughModal,
    DeleteContractFlowthroughModalProps,
} from 'src/components/contract-detail/delete-contract-flowthrough-modal';

describe('<DeleteContractFlowthroughModal />', () => {
    const render = (props: DeleteContractFlowthroughModalProps) =>
        renderInAppContext(<DeleteContractFlowthroughModal {...props} />);

    const deleteContractFlowthrough = jest.fn().mockResolvedValue({
        data: { abacusSoftDeleteContractFlowthrough: { deleted: true } },
        loading: false,
    });
    beforeEach(() =>
        jest
            .spyOn(
                contractFlowthroughMutations,
                'useSoftDeleteContractFlowthrough'
            )
            .mockReturnValue(deleteContractFlowthrough)
    );
    afterEach(jest.restoreAllMocks);

    const props: DeleteContractFlowthroughModalProps = {
        contractName: 'Test contract',
        contractFlowthroughId: '1',
        isDeleteFlowthroughModalOpen: true,
        onRequestCloseDeleteModal: jest.fn(),
    };

    it('renders delete contract flowthrough modal', () => {
        render(props);

        expect(screen.getByTestId('deleteContractFlowthrough')).toBeDefined();
    });

    it('renders modal content', () => {
        render(props);

        expect(
            screen.getByText('Delete flowthrough for this contract?')
        ).toBeDefined();
        expect(
            screen.getByTestId('deleteContractFlowthrough-content')
        ).toHaveTextContent(
            'Once you delete the flowthrough rules for this contract you will'
        );
    });

    it('renders a success toast popup on deleting flowthrough successfully', async () => {
        render(props);

        const deleteButton = screen.getByRole('button', { name: 'Delete' });
        await userEvent.setup().click(deleteButton);

        const toast = await screen.findByTestId('Toast-0');
        expect(toast).toBeDefined();
        expect(toast).toHaveTextContent(
            deleteContractFlowthroughMessage('Test contract')
        );
    });

    it('closes modal when isDeleteFlowthroughModalOpen is false', () => {
        render({ ...props, isDeleteFlowthroughModalOpen: false });
        expect(screen.queryByTestId('deleteContractFlowthrough')).toBeNull();
    });
});
