import React from 'react';
import { screen, fireEvent } from '@testing-library/react';
import { renderInAppContext } from '@theorchard/suite-testing';

import { AbacusStatementPeriodAdjustmentFileErrorType } from 'src/apollo/definitions/globalTypes';
import {
    AdjustmentsContext,
    AdjustmentsContextProps,
} from 'src/contexts/adjustments-context';
import { AdjustmentsUploadRowCountErrorScreen } from '../adjustments-upload-row-count-error-screen';

import { AdjustmentFile } from 'src/types/adjustment-file';

describe('<AdjustmentsUploadRowCountErrorScreen>', () => {
    const mockAdjustmentFileObj: AdjustmentFile = {
        actionStates: null,
        errorType: AbacusStatementPeriodAdjustmentFileErrorType.ROW_COUNT_ERROR,
        fileName: 'test.xlsx',
        invalidFileLocation: null,
        invalidRowCount: null,
        md5sum: null,
        statementPeriodAdjustmentFileId: 999,
        statementPeriodId: '123',
        totalFileAmountMulticurrency: null,
        totalRoundedAmountMulticurrency: null,
        validFileLocation: null,
        validRowCount: null,
    };

    const defaultContext: Partial<AdjustmentsContextProps> = {
        adjustmentFile: mockAdjustmentFileObj,
        resetToInitialState: jest.fn(),
    };

    const renderComponent = (
        contextValues: Partial<AdjustmentsContextProps> = {}
    ) => {
        const adjustmentsContext = {
            ...defaultContext,
            ...contextValues,
        } as AdjustmentsContextProps;

        return renderInAppContext(
            <AdjustmentsContext.Provider value={adjustmentsContext}>
                <AdjustmentsUploadRowCountErrorScreen />
            </AdjustmentsContext.Provider>
        );
    };

    it('renders the title', () => {
        renderComponent();

        const title = screen.getAllByText('Upload Failed')[0];
        expect(title).toBeDefined();
    });

    it('renders the alert', () => {
        renderComponent();

        const alert = screen.getByTestId('AdjustmentsRowCountErrorAlert');
        expect(alert).toHaveTextContent(
            'reduce the number of rows and try again'
        );
    });

    it('renders the upload area', () => {
        renderComponent();

        const uploadArea = screen.getByTestId(
            'AdjustmentsUploadRowCountErrorArea'
        );

        const input = uploadArea.querySelector(
            'input[type="file"]'
        ) as HTMLInputElement;

        expect(uploadArea).toHaveTextContent('Upload Failed');

        // The upload area is disabled so the file input should be hidden
        expect(input).toHaveStyle('display: none');
    });

    it('renders a button to reset to initial state', () => {
        renderComponent();

        const reUploadFileButton = screen.getByText('RE-UPLOAD FILE');
        fireEvent.click(reUploadFileButton);
        expect(defaultContext.resetToInitialState).toHaveBeenCalled();
    });
});
