import React from 'react';
import { screen } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import { contractEarningsTransferList } from 'src/__fixtures__/graphql/contract-earnings-transfers';
import { AbacusEarningsTransferTypesFilter } from 'src/apollo/definitions/globalTypes';
import * as earningsTransferQuery from 'src/apollo/queries/earnings-transfer';
import ContractEarningsTransferList, {
    ContractEarningsTransferListPropTypes,
} from 'src/components/contract-earnings-transfer-list/contract-earnings-transfer-list';
import { ContractEarningsTransferListColumns } from 'src/components/contract-earnings-transfer-list/contract-earnings-transfer-list-columns';
import { getContractDetail } from 'src/urls/frontend-royalties';

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useParams: jest.fn().mockReturnValue({ contractId: '500004' }),
}));

describe('<ContractEarningsTransferList>', () => {
    const defaultProps = {
        expanded: true,
        title: 'Override',
        transferType: AbacusEarningsTransferTypesFilter.OVERRIDE,
    };

    const render = (
        props: ContractEarningsTransferListPropTypes = defaultProps
    ) => renderInAppContext(<ContractEarningsTransferList {...props} />);

    beforeEach(() => {
        jest.spyOn(
            earningsTransferQuery,
            'useContractEarningsTransferList'
        ).mockReturnValue({
            data: {
                abacusEarningsTransfersByContractId: {
                    items: [
                        contractEarningsTransferList
                            .abacusEarningsTransfersByContractId.items[2],
                    ],
                    totalCount: 1,
                },
            },
            loading: false,
            error: undefined,
        });
    });

    it('renders transfer title and total count', () => {
        render(defaultProps);
        expect(screen.getByText('Override')).toBeDefined();

        const displayDiv = screen.getByTestId(
            'ContractEarningsTransfer-TotalCount'
        );
        expect(displayDiv.textContent.trim()).toMatch(/1\s+Transfer/);
    });

    it('renders a table with headers', () => {
        render(defaultProps);
        ContractEarningsTransferListColumns('123').forEach((header: any) =>
            expect(screen.getAllByText(header.title)).toBeDefined()
        );
    });

    it('show message when there are no override transfers', async () => {
        jest.spyOn(
            earningsTransferQuery,
            'useContractEarningsTransferList'
        ).mockReturnValue({
            data: {
                abacusEarningsTransfersByContractId: {
                    items: [],
                    totalCount: 0,
                },
            },
            loading: false,
            error: undefined,
        });
        render(defaultProps);
        const noFoundMsg = await screen.findByText(
            'No Override transfers added yet for this contract.'
        );

        expect(noFoundMsg).toBeDefined();
    });

    it('renders a list of override transfers', () => {
        render(defaultProps);
        const bodyText: any = [];
        document
            .querySelectorAll('div.GridTable-cell')
            .forEach((body: any) => bodyText.push(body.textContent));
        expect(bodyText).toEqual([
            '1',
            'In Sequence',
            'TEST GDA - DKKAccount:TEST GDA - DKKCurrent Contract',
            'TEST GDA - EURAccount:TEST GDA - EUR',
            '12,990,019.909',
            'Net Revenue',
            'Active',
            'No',
            '2026-05-07',
            '',
        ]);
        const links = screen.getAllByRole('link');
        expect(links[0].textContent).toEqual('TEST GDA - EUR');
        expect(links[0].getAttribute('href')).toContain(
            getContractDetail('500008')
        );
    });

    it('renders edit icon', () => {
        render(defaultProps);
        expect(screen.getByTestId('EditGlyphIcon')).toBeDefined();
        expect(
            screen
                .getByTestId('ContractEarningsTransfer-Edit')
                .getAttribute('href')
        ).toEqual('/contract/500004/earnings-transfer/1/edit');
    });

    it('renders a disabled edit icon when the contract is the "To Contract"', () => {
        const mockTransfer =
            contractEarningsTransferList.abacusEarningsTransfersByContractId
                .items[2];

        const invertedMockTransfer = {
            ...mockTransfer,
            fromContract: mockTransfer.toContract,
            toContract: mockTransfer.fromContract,
        };

        jest.spyOn(
            earningsTransferQuery,
            'useContractEarningsTransferList'
        ).mockReturnValue({
            data: {
                abacusEarningsTransfersByContractId: {
                    items: [invertedMockTransfer],
                    totalCount: 1,
                },
            },
            loading: false,
            error: undefined,
        });

        render(defaultProps);

        expect(
            screen.getByTestId('ContractEarningsTransfer-Edit-Disabled')
        ).toBeDefined();
    });
});
