import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import * as AppConfigModule from '@theorchard/suite-frontend';
import { Segment } from '@theorchard/suite-frontend';
import { mockAppConfig } from 'lib/test-helpers/factories';
import { createIdentity } from 'lib/test-utils/identity-factory';
import { services } from 'src/services/user';
import IdentityContext from '../../../../context';
import AppSwitcher from '../app-switcher';

jest.mock('@theorchard/suite-frontend', () => ({
    __esModule: true,
    ...jest.requireActual('@theorchard/suite-frontend'),
}));

const userAvailableApps = [
    {
        id: 'INSIGHTS_APP',
        name: 'Insights app',
        url: 'https://insights.theorchard.com',
    },
    {
        id: 'SETTINGS_APP',
        name: 'Settings app',
        url: 'https://settings.theorchard.com',
    },
    {
        id: 'MONEYHUB_APP',
        name: 'Accounting app',
        url: 'https://moneyhub.theorchard.com',
    },
];

describe('<AppSwitcher>', () => {
    const identity = createIdentity({
        id: 1,
        accountType: 'vendor',
        accountId: '12345',
    });
    identity.identityId = '7988bbae-086e-4a96-8e65-fd21b07305ef';

    beforeEach(() => {
        jest.spyOn(AppConfigModule, 'useAppConfig').mockReturnValue({
            ...mockAppConfig,
            environment: 'prod',
        });
        jest.spyOn(services, 'getGqlUserApplications').mockResolvedValue(
            userAvailableApps
        );
        jest.spyOn(Segment, 'trackEvent').mockImplementation(jest.fn());
        jest.spyOn(window, 'open').mockImplementation(jest.fn());
    });

    const renderComponent = () =>
        render(
            <IdentityContext.Provider
                value={{ identity, hasAuthentication: () => false }}
            >
                <AppSwitcher />
            </IdentityContext.Provider>
        );

    test('renders AppSwitcher component with 2 available apps (with suite-icons)', async () => {
        renderComponent();

        const btn = await screen.findByTestId('openPopoverButton');

        fireEvent.click(btn);

        const app1 = await screen.findByText('Insights app');
        const app2 = await screen.findByText('Settings app');

        const appIcon1 = await screen.findByTestId('InsightsAppIcon');
        const appIcon2 = await screen.findByTestId('SettingsAppIcon');

        expect(app1).toBeInTheDocument();
        expect(app2).toBeInTheDocument();
        expect(appIcon1).toBeInTheDocument();
        expect(appIcon2).toBeInTheDocument();
    });

    test('calls track event and opens new window on click', async () => {
        renderComponent();
        const firstApp = userAvailableApps[0];

        const btn = await screen.findByTestId('openPopoverButton');
        fireEvent.click(btn);

        const appLink = await screen.findByText(firstApp.name);
        fireEvent.click(appLink);

        expect(Segment.trackEvent).toHaveBeenCalledWith(
            `Click - AppSwitcher - ${firstApp.name}`
        );
        expect(window.open).toHaveBeenCalledWith(firstApp.url, '_blank');
    });

    test('redirects to resource based url on Accounting click', async () => {
        renderComponent();
        const accountingApp = userAvailableApps[2];

        const btn = await screen.findByTestId('openPopoverButton');
        fireEvent.click(btn);

        const appLink = await screen.findByText(accountingApp.name);
        fireEvent.click(appLink);

        expect(Segment.trackEvent).toHaveBeenCalledWith(
            `Click - AppSwitcher - ${accountingApp.name}`
        );
        expect(window.open).toHaveBeenCalledWith(
            'https://accounting.theorchard.com/account/12345/highlights/overview',
            '_blank'
        );
    });
});
