import React from 'react';
import { screen, waitFor } from '@testing-library/react';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom';
import { NetworkStatus } from '@apollo/client';
import { renderInAppContext } from '@theorchard/suite-testing';
import * as featureFlags from 'src/utils/features';
import * as getBulkSessionIngestions from 'src/data/queries/getBulkSessionIngestions';
import AdminPage from '..';

const mockUseGetBulkSessionIngestionsQuery = (overrides = {}) => {
    jest.spyOn(
        getBulkSessionIngestions,
        'useGetBulkSessionIngestionsQuery'
    ).mockReturnValue({
        data: null,
        loading: false,
        error: undefined,
        fetchMore: jest.fn(),
        networkStatus: NetworkStatus.ready,
        ...overrides,
    });
};

describe('AdminPage', () => {
    beforeEach(() => {
        jest.spyOn(featureFlags, 'useCcmBulkPowerUserTechWeek').mockReturnValue(
            true
        );
        mockUseGetBulkSessionIngestionsQuery();
    });

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

    test('redirects to root when the feature flag is disabled', async () => {
        jest.spyOn(featureFlags, 'useCcmBulkPowerUserTechWeek').mockReturnValue(
            false
        );

        const history = createMemoryHistory({
            initialEntries: ['/create/digital-audio/bulk/admin'],
        });

        renderInAppContext(
            <Router history={history}>
                <AdminPage />
            </Router>
        );

        await waitFor(() => {
            expect(history.location.pathname).toBe('/');
        });
    });

    test('renders page title when the feature flag is enabled', () => {
        const history = createMemoryHistory({
            initialEntries: ['/create/digital-audio/bulk/admin'],
        });

        renderInAppContext(
            <Router history={history}>
                <AdminPage />
            </Router>
        );

        expect(screen.getByText('Bulk Session Ingestions')).toBeInTheDocument();
        expect(history.location.pathname).toBe(
            '/create/digital-audio/bulk/admin'
        );
    });

    test('passes query data to BulkSessionIngestionList', () => {
        const items = [
            {
                id: 'ing-1',
                ingestionStatus: 'success',
                completedOn: null,
                bulkSession: {
                    id: 'sess-1',
                    slug: 'sess-slug-1',
                    downloadLink: null,
                    totalProducts: null,
                    createdBy: null,
                    label: { __typename: 'Subaccount' },
                },
            },
            {
                id: 'ing-2',
                ingestionStatus: 'failed',
                completedOn: null,
                bulkSession: {
                    id: 'sess-2',
                    slug: 'sess-slug-2',
                    downloadLink: null,
                    totalProducts: null,
                    createdBy: null,
                    label: { __typename: 'Subaccount' },
                },
            },
        ];
        mockUseGetBulkSessionIngestionsQuery({
            data: { items, total: 2 },
        });

        const history = createMemoryHistory({
            initialEntries: ['/create/digital-audio/bulk/admin'],
        });

        renderInAppContext(
            <Router history={history}>
                <AdminPage />
            </Router>
        );

        expect(screen.getByText('sess-slug-1')).toBeInTheDocument();
        expect(screen.getByText('sess-slug-2')).toBeInTheDocument();
    });

    test('passes fetchMore function to BulkSessionIngestionList', () => {
        const fetchMore = jest.fn();
        mockUseGetBulkSessionIngestionsQuery({
            data: { items: [], total: 0 },
            fetchMore,
        });

        const history = createMemoryHistory({
            initialEntries: ['/create/digital-audio/bulk/admin'],
        });

        renderInAppContext(
            <Router history={history}>
                <AdminPage />
            </Router>
        );

        // Component should render without errors
        expect(screen.getByText('Bulk Session Ingestions')).toBeInTheDocument();
    });

    test('sets correct loading state during fetchMore', () => {
        mockUseGetBulkSessionIngestionsQuery({
            data: { items: [], total: 0 },
            networkStatus: NetworkStatus.fetchMore,
        });

        const history = createMemoryHistory({
            initialEntries: ['/create/digital-audio/bulk/admin'],
        });

        const { container } = renderInAppContext(
            <Router history={history}>
                <AdminPage />
            </Router>
        );

        // Should pass loading as true when networkStatus is fetchMore
        expect(
            container.querySelector('[data-testid="GridTable"]')
        ).toHaveClass('loading');
    });
});
