import React from 'react';
import * as apollo from '@apollo/client';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as useReleaseAbacusAccountPayeeMutation from 'src/apollo/mutations/release-abacus-account-payee';
import ReleasePayeeModal, {
    ReleasePayeeModalPropTypes,
} from '../release-payee-modal';

describe('<PayeeFieldsPayoneer> layout', () => {
    const defaultProps = {
        accountPayeeId: '2',
        paymentPendingInCurrentStatementPeriod: null,
    };

    const render = (props: ReleasePayeeModalPropTypes) =>
        renderInAppContext(<ReleasePayeeModal {...props} />);

    beforeEach(() => {
        const client = {} as apollo.QueryResult<unknown, unknown>;
        jest.spyOn(apollo, 'useQuery').mockReturnValue(client);
    });

    afterEach(() => {
        jest.clearAllMocks();
    });

    it('render with default props', async () => {
        const { container } = render(defaultProps);
        expect(container).toBeDefined();
        const btnRelease = await screen.findByRole('button', {
            name: 'Release Payee from Payoneer',
        });
        expect(btnRelease).toBeDefined();
        expect(btnRelease.hasAttribute('disabled')).toBe(false);
        expect(container.querySelector('#PaymentPendingTooltip')).toBeNull();
    });

    it('if paymentPendingInCurrentStatementPeriod', async () => {
        const { container } = render({
            ...defaultProps,
            paymentPendingInCurrentStatementPeriod: {
                accountId: '',
            },
        });

        const btnRelease = await screen.findByRole('button', {
            name: 'Release Payee from Payoneer',
        });
        expect(btnRelease).toBeDefined();
        expect(btnRelease.hasAttribute('disabled')).toBe(true);
        expect(container.querySelector('#PaymentPendingTooltip')).toBeDefined();
    });

    it('release payee from Payoneer', async () => {
        const releaseAccountPayee = jest
            .spyOn(
                useReleaseAbacusAccountPayeeMutation,
                'useReleaseAbacusAccountPayeeHook'
            )
            .mockReturnValue({
                releasePayeeMutationResponse: null,
                loading: false,
            });

        render(defaultProps);

        const btnRelease = screen.getByTestId('buttonRelease');
        fireEvent.click(btnRelease);

        await waitFor(() => {
            expect(
                screen.getByText('Release Payee from Payoneer?')
            ).toBeDefined();
            expect(screen.getByText('cancel')).toBeDefined();
        });

        const btnConfirm = await screen.findByRole('button', {
            name: 'Confirm changes',
        });
        fireEvent.click(btnConfirm);
        await waitFor(() => {
            expect(releaseAccountPayee).toHaveBeenCalled();
        });
    });
});
