import React from 'react';
import { fireEvent, render } from '@testing-library/react';
import { IdentityContext } from '@theorchard/suite-identity';
import { AppSwitcher, Props } from '../appSwitcher';

const identity = {
    id: 'some-id',
    name: 'Mike Patton',
    features: {},
};

describe('<AppSwitcher>', () => {
    const INSIGHTS_APP = {
        id: 'INSIGHTS_APP',
        name: 'Insights',
        url: 'https://insights.qaorch.com',
    };
    const WORKSTATION_APP = {
        id: 'WORKSTATION_APP',
        name: 'Workstation',
        url: 'https://workstation.qaorch.com',
    };
    const SETTINGS_APP = {
        id: 'SETTINGS_APP',
        name: 'Settings',
        url: 'https://settings.qaorch.com',
    };

    const appSwitcherApps = [INSIGHTS_APP, WORKSTATION_APP, SETTINGS_APP];

    const defaultProps = {
        applications: appSwitcherApps,
    };

    const renderComponent = (props: Partial<Props> = {}) =>
        render(
            <IdentityContext.Provider value={{ identity }}>
                <AppSwitcher {...defaultProps} {...props} />
            </IdentityContext.Provider>
        );

    const openAppSwitcher = async () => {
        const { getByTestId, findAllByTestId } = renderComponent();

        const openButton = getByTestId('AppSwitcher');
        fireEvent.click(openButton);

        return await findAllByTestId('AppGridButton');
    };

    test('renders correctly and has classname', () => {
        const { container } = renderComponent();
        expect(container.getElementsByClassName('AppSwitcher').item(0)).toBeVisible();
    });

    test('renders old icon and text without prop asNavLink', () => {
        const { getByTestId, container } = renderComponent();

        expect(getByTestId('AppsNavIcon')).toBeInTheDocument();
        expect(container.getElementsByClassName('NavLink-title').item(0)).not.toBeInTheDocument();
    });

    test('renders icon and text with prop asNavLink=true', () => {
        const { getByTestId, container } = renderComponent({ asNavLink: true });

        expect(getByTestId('AppsGlyphIcon')).toBeInTheDocument();
        expect(container.getElementsByClassName('NavLink-title').item(0)).toBeVisible();
    });

    describe('when clicked', () => {
        test('shows an overlay with links for each passed apps', async () => {
            const appGridItems = await openAppSwitcher();

            expect(appGridItems).toHaveLength(appSwitcherApps.length);
        });

        test('app links have urls and target blank', async () => {
            const [app] = appSwitcherApps;
            const [appGridItem] = await openAppSwitcher();

            expect(appGridItem).toHaveAttribute('href', app.url);
            expect(appGridItem).toHaveAttribute('target', '_blank');
            expect(appGridItem).toHaveTextContent(app.name);
        });
    });
});
