import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { IdentityContext, Identity } from '@theorchard/suite-identity';
import Segment from '../../../segment';
import { AppGridButton } from '../appGridButton';

describe('<AppGridButton>', () => {
    const defaultApp = {
        id: 'INSIGHTS_APP',
        name: 'Insights',
        url: 'https://insights.qaorch.com',
    };

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

    const renderComponent = (app = defaultApp, identity: Identity = defaultIdentity) =>
        render(
            <IdentityContext.Provider value={{ identity }}>
                <AppGridButton app={app} />
            </IdentityContext.Provider>
        );

    beforeEach(() => {
        vi.spyOn(Segment, 'trackEvent').mockImplementation(vi.fn());
    });

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

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

        expect(button).toBeVisible();
    });

    test('have url and target blank', () => {
        const { container } = renderComponent();
        const button = container.getElementsByClassName('AppGridButton').item(0);

        expect(button).toHaveAttribute('href', defaultApp.url);
        expect(button).toHaveAttribute('target', '_blank');
    });

    test('renders Insights logo', () => {
        const { getByTestId } = renderComponent();

        const appIconElement = getByTestId('InsightsAppIcon');

        expect(appIconElement).toBeInTheDocument();
    });

    test('renders the application name', () => {
        renderComponent();

        const appNameElement = screen.getByText(defaultApp.name);

        expect(appNameElement).toBeInTheDocument();
    });

    test('appends impersonating param when session is impersonated', () => {
        const { container } = renderComponent(defaultApp, {
            ...defaultIdentity,
            impersonatedBy: { id: 'lol' },
        });
        const button = container.getElementsByClassName('AppGridButton').item(0);

        expect(button).toHaveAttribute(
            'href',
            `${defaultApp.url}?impersonating=${defaultIdentity.id}`
        );
        expect(button).toHaveAttribute('target', '_blank');
    });

    test('calls track event on click', () => {
        renderComponent();

        const link = screen.getByTestId('AppGridButton');
        fireEvent.click(link);

        expect(Segment.trackEvent).toHaveBeenCalledWith(`Click - AppSwitcher - ${defaultApp.name}`);
    });
});
