import React from 'react';
import { Alert } from '@theorchard/suite-components';
import { Sentry } from '@theorchard/suite-frontend';
import cx from 'classnames';
import htmlParse from 'html-react-parser';
import IdentityContext from 'src/context';
import { services } from 'src/services/user';
import { formatMessage } from 'src/utils';
import { getImpersonationNotification } from 'src/utils/IdentityManager';
import type { SuiteNotification } from '@theorchard/suite-frontend';

const CLASS_NAME = 'SuiteNotificationBanner';

export const SuiteNotificationBanner = () => {
    const { identity } = React.useContext(IdentityContext);
    const [notifications, setNotifications] = React.useState<
        SuiteNotification[]
    >([]);

    React.useEffect(() => {
        if (!identity?.identityId) return;

        services
            .getGqlUserSuiteNotifications(identity?.identityId)
            .then((notifications: SuiteNotification[]) => {
                setNotifications([
                    ...notifications,
                    ...(getImpersonationNotification(
                        identity
                    ) as SuiteNotification[]),
                ]);
            })
            .catch((error: Error) => {
                Sentry.captureException(error);
            });
    }, [identity]);

    if (!notifications?.length) return null;

    return (
        <div
            className={cx(CLASS_NAME, 'WorkstationSuiteComponents')}
            data-testid={CLASS_NAME}
        >
            {notifications.map(notification => {
                const intlMsg = formatMessage(
                    `suiteNotification.${notification.id}__message`,
                    notification.messageData
                );
                const intlLinkText = formatMessage(
                    `suiteNotification.${notification.id}__linkText`,
                    notification.messageData
                );
                return (
                    <Alert
                        key={notification.id}
                        testId={`${CLASS_NAME}-Alert`}
                        variant={notification.variant}
                        text={htmlParse(intlMsg)}
                        button={{
                            text: intlLinkText,
                            onClick: () => {
                                if (notification.link) {
                                    window.open(
                                        notification.link,
                                        notification.id === 'impersonation'
                                            ? '_self'
                                            : '_blank'
                                    );
                                }
                            },
                        }}
                    />
                );
            })}
        </div>
    );
};

export default SuiteNotificationBanner;
