import React from 'react';
import { screen } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as updateEarningsTransferHook from 'src/hooks/contract-earnings-transfer/update-contract-earnings-transfer';
import * as earningsTransferQuery from 'src/apollo/queries/earnings-transfer';
import { ContractEarningsTransferFullScreenModal } from '../contract-earnings-transfer-fullscreen-modal';
import { contractEarningsTransferById } from 'src/__fixtures__/graphql/contract-earnings-transfers';

// jsdom does not implement crypto.randomUUID; stub it
Object.defineProperty(global, 'crypto', {
    value: { randomUUID: () => 'test-uuid' },
    configurable: true,
});

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useParams: () => ({
        contractId: 'contract-123',
        earningsTransferId: 'transfer-123',
    }),
}));

describe('<ContractEarningsTransferFullScreenModal />', () => {
    const render = () =>
        renderInAppContext(<ContractEarningsTransferFullScreenModal />);

    beforeEach(() => {
        jest.spyOn(
            earningsTransferQuery,
            'useEarningsTransferById'
        ).mockReturnValue({
            data: contractEarningsTransferById,
            loading: false,
            error: undefined,
        });
    });

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

    describe('Modal render', () => {
        it('renders the Save button', () => {
            render();

            const button = screen.getByTestId('earningsTransferSaveButton');
            expect(button).toBeDefined();
            expect(button).toHaveTextContent('Save');
        });

        it('renders the config screen directly with columns pre-populated', () => {
            render();

            expect(
                screen.getByTestId('earningsTransferFromContract-0')
            ).toBeDefined();
            expect(screen.getAllByText('TEST GDA - EUR')).toBeDefined();
        });
    });

    describe('Save handler', () => {
        it('calls useSaveHandler with the current contractId', () => {
            const useSaveHandlerSpy = jest
                .spyOn(updateEarningsTransferHook, 'useUpdateHandler')
                .mockReturnValue(jest.fn().mockResolvedValue(undefined));

            render();

            expect(useSaveHandlerSpy).toHaveBeenCalledWith('contract-123');
        });
    });
});
