import React from 'react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as exchangeRateMutations from 'src/apollo/mutations/exchange-rate';
import {
    UploadExchangeRates,
    UploadExchangeRatesProps,
} from 'src/components/statement-period-detail/upload-exchange-rates';

const render = (props: UploadExchangeRatesProps) =>
    renderInAppContext(<UploadExchangeRates {...props} />);

describe('<UploadExchangeRates>', () => {
    const uploadExchangeRates = jest.fn().mockResolvedValue({});

    beforeEach(() => {
        jest.spyOn(
            exchangeRateMutations,
            'useUploadExchangeRates'
        ).mockReturnValue(uploadExchangeRates);
        const mockFileReader: any = {
            result: 'data',
            readAsBinaryString: () => {
                jest.fn();
            },
            onload: () => {
                uploadExchangeRates();
            },
        };
        jest.spyOn(window, 'FileReader').mockImplementation(
            () => mockFileReader
        );
        jest.spyOn(mockFileReader, 'readAsBinaryString').mockImplementation(
            () => {
                mockFileReader.result = 'data';
                mockFileReader.onload();
            }
        );
    });

    afterEach(jest.restoreAllMocks);

    it('renders when exchange rates for statement period is not uploaded', () => {
        const props = {
            exchangeRatesUploaded: false,
            setError: jest.fn(),
        };
        render(props);
        expect(screen.getByText('UPLOAD EXCHANGE RATES')).toBeDefined();
    });

    it('upload exchange rate file', async () => {
        const props = {
            exchangeRatesUploaded: false,
            setError: jest.fn(),
        };
        const { container } = render(props);
        const file = new File(['data'], 'some.csv');
        const fileInputField = screen.getByLabelText('UPLOAD EXCHANGE RATES');
        expect(fileInputField).toBeTruthy();

        Object.defineProperty(fileInputField, 'files', { value: [file] });
        fireEvent.drop(fileInputField);

        await waitFor(() => {
            expect(container.querySelectorAll('.SkeletonLoader').length).toBe(
                1
            );
            expect(uploadExchangeRates).toHaveBeenCalled();
        });
    }, 10000);

    it('renders when exchange rates for statement period is uploaded', () => {
        const props = {
            exchangeRatesUploaded: true,
            setError: jest.fn(),
        };
        render(props);
        expect(screen.getByText('Exchange Rates')).toBeDefined();
    });
});
