import React from 'react';
import { fireEvent } from '@testing-library/react';
import { Segment } from '@theorchard/suite-frontend';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as canPerformQueries from 'src/data/queries/canPerform/canPerform';
import * as queries from 'src/data/queries/getRecentNrIngestions/getRecentNrIngestions';
import { usePPEnabledFF } from 'src/utils/features';
import ViewBulkUploads from '../viewBulkUploads';
import type { NrIngestionFile } from 'src/data/queries/getRecentNrIngestions/types';

jest.mock('src/utils/features', () => ({
    usePPEnabledFF: jest.fn(),
}));
const usePPEnabledFFMock = usePPEnabledFF as jest.Mock;
const canPerformActionMock = jest.spyOn(
    canPerformQueries,
    'useCanPerformAction'
);

describe('<ViewBulkUploads>', () => {
    const renderWrapper = () => renderInAppContext(<ViewBulkUploads />);
    const mockQueries = (data: NrIngestionFile[]) => {
        jest.spyOn(
            queries,
            'useGetRecentIngestionsFileProgress'
        ).mockReturnValue({
            data,
            error: undefined,
            stopPolling: jest.fn(),
            startPolling: jest.fn(),
        });
    };

    beforeEach(() => {
        mockQueries([]);
    });

    test('renders ViewBulkUploads button', () => {
        const { getByText } = renderWrapper();
        expect(
            getByText($t('neighbouringRights.viewBulkUploads.bulkUploads'))
        ).toBeVisible();
    });

    describe('on click ViewBulkUploads button', () => {
        test('it shows active and completed uploads', async () => {
            const data = [
                {
                    lastModified: '2022-03-03T09:40:14.000Z',
                    originalFilename: 'killjoys.csv',
                    id: 'ddb77517-0012-4ebe-b5eb-bf03e461d3ab.csv',
                    identity: {
                        id: 'some-id',
                        firstName: 'Allan',
                        lastName: 'Moon',
                    },
                    successRows: 100,
                    errorRows: 0,
                    totalRows: 100,
                    ingestionCompleted: true,
                    successFileUrl:
                        'https://qa-nr/ingestion/ddb77517-0012-4ebe-b5eb-bf03e461d3ab/success.csv',
                    errorFileUrl: '',
                },
                {
                    lastModified: '2022-03-03T05:02:13.000Z',
                    originalFilename: 'star_trek.csv',
                    id: '6a5ac6a5-7749-446d-a483-677449051689.csv',
                    identity: {
                        id: 'some-id',
                        firstName: 'Allan',
                        lastName: 'Moon',
                    },
                    successRows: 10,
                    errorRows: 5,
                    totalRows: 15,
                    ingestionCompleted: true,
                    successFileUrl:
                        'https://qa-nr/ingestion/6a5ac6a5-7749-446d-a483-677449051689/success.csv',
                    errorFileUrl:
                        'https://qa-nr/ingestion/6a5ac6a5-7749-446d-a483-677449051689/error.csv',
                },
                {
                    lastModified: '2022-03-01T13:25:46.000Z',
                    originalFilename: 'Doctor-Who.csv',
                    id: '8060aa56-5838-4791-b558-d12ca5c5e095.csv',
                    identity: {
                        id: 'some-id',
                        firstName: 'Allan',
                        lastName: 'Moon',
                    },
                    successRows: 0,
                    errorRows: 3,
                    totalRows: 3,
                    ingestionCompleted: false,
                    successFileUrl: '',
                    errorFileUrl:
                        'https://qa-nr/ingestion/8060aa56-5838-4791-b558-d12ca5c5e095/error.csv',
                },
            ];
            mockQueries(data);
            const { getByText, findByTestId } = renderWrapper();
            const viewButton = getByText(
                $t('neighbouringRights.viewBulkUploads.bulkUploads')
            );
            expect(viewButton).toBeTruthy();

            fireEvent.click(viewButton);
            const fileOne = await findByTestId(
                'ddb77517-0012-4ebe-b5eb-bf03e461d3ab.csv'
            );
            const fileTwo = await findByTestId(
                '6a5ac6a5-7749-446d-a483-677449051689.csv'
            );
            const fileThree = await findByTestId(
                '8060aa56-5838-4791-b558-d12ca5c5e095.csv'
            );

            expect(fileOne).toBeTruthy();
            expect(fileTwo).toBeTruthy();
            expect(fileThree).toBeTruthy();
            expect(getByText(/killjoys\.csv/)).toBeTruthy();
            expect(getByText(/star_trek\.csv/)).toBeTruthy();
        });
    });

    describe('on clicking Close button', () => {
        const segmentTrack = jest.spyOn(Segment, 'trackEvent');
        test('tracks event', () => {
            const { getByText, getAllByRole } = renderWrapper();
            const viewButton = getByText(
                $t('neighbouringRights.viewBulkUploads.bulkUploads')
            );
            fireEvent.click(viewButton);
            const closeButton = getAllByRole('button')[1];
            if (closeButton) fireEvent.click(closeButton);
            expect(segmentTrack).toHaveBeenLastCalledWith(
                'Click',
                { category: 'Content Sound Recording Performances' },
                'Close Bulk Uploads'
            );
        });
    });

    describe('when usePPEnabledFF is true', () => {
        beforeEach(() => {
            usePPEnabledFFMock.mockReturnValue(true);
        });

        describe('and user has create NrContribution permissions', () => {
            beforeEach(() => {
                canPerformActionMock.mockReturnValue({
                    data: true,
                    loading: false,
                    error: undefined,
                });
            });
            test('renders the component', () => {
                const { getByText } = renderWrapper();
                expect(
                    getByText(
                        $t('neighbouringRights.viewBulkUploads.bulkUploads')
                    )
                ).toBeTruthy();
            });
        });
        describe('and user does not have create NrContribution permissions', () => {
            beforeEach(() => {
                canPerformActionMock.mockReturnValue({
                    data: false,
                    loading: false,
                    error: undefined,
                });
            });
            test('does not render the component', () => {
                const { getByText } = renderWrapper();
                expect(() =>
                    getByText(
                        $t('neighbouringRights.viewBulkUploads.bulkUploads')
                    )
                ).toThrow(Error);
            });
        });
    });
});
