import React, { useState, useEffect, useContext } from 'react';
import {
    OverlayTrigger,
    Button,
    Popover,
    GridGlyph,
} from '@orchard/frontend-react-components';
import { Segment, useAppConfig } from '@theorchard/suite-frontend';
import { AppIcon } from '@theorchard/suite-icons';
import IdentityContext from 'src/context';
import { services } from 'src/services/user';
import { getEnvironmentBrandedLinkAccounting } from '../header';

const CLASSNAME = 'AppSwitcher';

const openOnNewTab = (url: string) => window.open(url, '_blank');

interface App {
    id: string;
    name: string;
    url: string;
}

const AppSwitcher: React.FC = () => {
    const config = useAppConfig();
    const { identity } = useContext(IdentityContext);
    const userIdentityId = identity?.identityId;
    const [availableApps, setAvailableApps] = useState<App[] | null>(null);

    useEffect(() => {
        if (userIdentityId)
            void services.getGqlUserApplications(userIdentityId).then(apps => {
                setAvailableApps(apps as App[]);
            });
    }, [userIdentityId]);

    const renderAppButton = (app: App) => (
        <div
            key={app.id}
            role="button"
            tabIndex={0}
            className="GridItem"
            data-testid="appGridItem"
            onClick={() => {
                void Segment.trackEvent(`Click - AppSwitcher - ${app.name}`);

                const accountingUrl = getEnvironmentBrandedLinkAccounting(
                    config,
                    identity
                );
                openOnNewTab(
                    app.name.includes('Accounting') ? accountingUrl : app.url
                );
            }}
            onKeyPress={() => openOnNewTab(app.url)}
        >
            <div className="AppButton">
                <AppIcon app={app.id} />
            </div>
            <span className="AppName">{app.name}</span>
        </div>
    );

    if (!availableApps) return null;

    const renderPopupOverlay = () => (
        <Popover id="AppSwitcherPopover">
            <Popover.Content className="AppGrid">
                {availableApps.map(renderAppButton)}
            </Popover.Content>
        </Popover>
    );

    return (
        <div className={CLASSNAME}>
            <OverlayTrigger
                placement="bottom"
                trigger="click"
                rootClose
                overlay={renderPopupOverlay()}
            >
                <Button
                    block
                    variant="link"
                    className="text-white px-2"
                    data-testid="openPopoverButton"
                >
                    <GridGlyph />
                </Button>
            </OverlayTrigger>
        </div>
    );
};

export default AppSwitcher;
