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

import {
    AdjustmentsContext,
    AdjustmentsContextProps,
} from 'src/contexts/adjustments-context';
import { AdjustmentsUploadFailedScreen } from '../adjustments-upload-failed-screen';

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

describe('<AdjustmentUploadFailedScreen>', () => {
    const mockAdjustmentFileObj: AdjustmentFile = {
        actionStates: null,
        errorType: '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,
        handleModalClose: jest.fn(),
        resetToInitialState: jest.fn(),
    };

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

        return renderInAppContext(
            <AdjustmentsContext.Provider value={adjustmentsContext}>
                <AdjustmentsUploadFailedScreen />
            </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('AdjustmentsUploadFailedAlert');
        expect(alert).toHaveTextContent('Internal Error');
    });

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

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

        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 when clicked', () => {
        renderComponent();

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