import React from 'react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { type FeatureFlagDictionary } from '@theorchard/suite-frontend';
import { createIdentity, renderInAppContext } from '@theorchard/suite-testing';
import * as paymentGroupPaymentMutations from 'src/apollo/mutations/payment-group-payment';
import PaymentGroupDetailOptions from 'src/components/payment-group-detail/payment-group-detail-options';
import { USER_FEATURES } from 'src/constants';

const defaultProps = {
    paymentGroupPaymentId: '1',
    paymentGroupPaymentStatus: 'send_for_approval',
};

const render = (features: FeatureFlagDictionary) =>
    renderInAppContext(<PaymentGroupDetailOptions {...defaultProps} />, {
        identity: createIdentity({ features }),
    });

describe('<PaymentGroupDetailOptions/>', () => {
    const deletePaymentGroupPayment = jest.fn().mockResolvedValue({});
    const realCreateRange = global.document.createRange;
    const features: FeatureFlagDictionary = {
        [USER_FEATURES.ABACUS_CREATE_AND_APPROVE_PAYMENTS]: true,
    };

    afterEach(() => {
        global.document.createRange = realCreateRange;
        jest.restoreAllMocks();
    });

    beforeEach(() => {
        global.document.createRange = () => ({
            setStart: () => {},
            setEnd: () => {},
            // @ts-expect-error: ignore missing properties error
            commonAncestorContainer: {
                nodeName: 'BODY',
                ownerDocument: document,
            },
        });

        jest.spyOn(
            paymentGroupPaymentMutations,
            'useDeletePaymentGroupPayment'
        ).mockReturnValue({ deletePaymentGroupPayment, loading: false });
    });

    it('displays trashcan delete button', () => {
        render(features);

        const deleteButton = screen.getByTestId('TrashGlyphIcon');
        expect(deleteButton).toBeTruthy();
        expect(deleteButton).not.toBeDisabled();
    });

    it('displays confirm popup when delete button is clicked', () => {
        const { container } = render(features);
        const deleteButton =
            container.querySelector('.deleteButton') ?? new Element();
        fireEvent.click(deleteButton);

        expect(
            screen.getByText('Deleting this payment will be permanent.')
        ).toBeTruthy();
    });

    it('invokes delete request when confirm button is clicked', async () => {
        const { container } = render(features);
        const deleteButton =
            container.querySelector('.deleteButton') ?? new Element();
        fireEvent.click(deleteButton);

        const confirmButton = screen.getByText('Delete Payment');
        fireEvent.click(confirmButton);

        await waitFor(() => {
            expect(deletePaymentGroupPayment).toHaveBeenCalled();
        });
    });

    it("doesn't render delete icon if FF is disabled", () => {
        render({
            [USER_FEATURES.ABACUS_CREATE_AND_APPROVE_PAYMENTS]: false,
        });

        const deleteButton = screen.queryByTestId('TrashGlyphIcon');
        expect(deleteButton).toBeNull();
    });
});
