import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2024-2026 GoodData Corporation
import { Fragment, useCallback } from "react";
import { compact } from "lodash-es";
import { FormattedDate, FormattedMessage, FormattedTime, defineMessages, useIntl } from "react-intl";
import { Bubble, BubbleHoverTrigger, UiButton, UiIcon, UiIconButton, getDateTimeConfig, isActionKey, useToastMessage, } from "@gooddata/sdk-ui-kit";
import { bem } from "../bem.js";
import { Popup } from "../components/Popup.js";
import { Tooltip } from "../components/Tooltip.js";
import { NotificationFiltersDetail } from "../NotificationFiltersDetail/NotificationFiltersDetail.js";
import { NotificationTriggerDetail } from "../NotificationTriggersDetail/NotificationTriggersDetail.js";
import { downloadFiles } from "../utils/downloadFiles.js";
const { b, e } = bem("gd-ui-ext-notification");
function handleScheduleNotificationClick(exports, isExpired, addWarning) {
    if (isExpired) {
        addWarning(messages.notificationExpired);
        return;
    }
    const downloadableExports = compact(exports.map(mapToDownloadableFile));
    if (downloadableExports.length > 0) {
        void downloadFiles(downloadableExports);
    }
}
function handleAlertNotificationClick(notification, closeNotificationsPanel, onNotificationClick) {
    closeNotificationsPanel();
    onNotificationClick?.(notification);
}
/**
 * @internal
 */
export function Notification({ notification, markNotificationAsRead, onNotificationClick, closeNotificationsPanel, }) {
    const intl = useIntl();
    const { addWarning } = useToastMessage();
    const notificationTitle = getNotificationTitle(notification);
    const filters = notification.details.data.filters;
    const hasFilters = !!filters?.length;
    const isAlertNotification = notification.notificationType === "alertNotification";
    const isScheduleNotification = notification.notificationType === "scheduleNotification";
    const isSliced = isAlertNotification && !!notification.details.data.alert.attribute;
    const hasTriggers = isAlertNotification && !!notification.details.data.alert.totalValueCount;
    const exports = compact([
        notification.details.data.visualExports,
        notification.details.data.tabularExports,
        notification.details.data.imageExports,
        notification.details.data.rawExports,
        notification.details.data.slidesExports,
        notification.details.data.dashboardTabularExports,
    ]).flatMap((arr) => arr ?? []);
    const hasExports = exports.length > 0;
    const fileExpiresAt = exports?.[0]?.expiresAt ?? null;
    const isExpired = fileExpiresAt != null && new Date(fileExpiresAt) < new Date();
    const { isError, errorTitle, errorMessage, traceId } = getNotificationErrorInfo(notification, exports);
    const actions = compact([
        hasFilters && isAlertNotification && _jsx(NotificationFiltersDetail, { filters: filters }),
        hasTriggers && isSliced && _jsx(NotificationTriggerDetail, { notification: notification }),
        hasExports && _jsx(FileLink, { notification: notification }),
        hasExports && fileExpiresAt && _jsx(FileExpiration, { fileExpiresAt: fileExpiresAt, isExpired: isExpired }),
    ]);
    const handleNotificationClick = useCallback(() => {
        if (!notification.isRead) {
            markNotificationAsRead(notification.id);
        }
        if (notification.notificationType === "scheduleNotification") {
            handleScheduleNotificationClick(exports, isExpired, addWarning);
        }
        else {
            handleAlertNotificationClick(notification, closeNotificationsPanel, onNotificationClick);
        }
    }, [
        onNotificationClick,
        notification,
        isExpired,
        markNotificationAsRead,
        closeNotificationsPanel,
        addWarning,
        exports,
    ]);
    const handleKeyDown = (event) => {
        if (isActionKey(event)) {
            event.preventDefault();
            handleNotificationClick();
        }
    };
    return (_jsxs(BubbleHoverTrigger, { enabled: hasExports && !isExpired ? !isError : undefined, children: [_jsxs("div", { className: b({ isRead: notification.isRead }), onClick: handleNotificationClick, onKeyDown: handleKeyDown, role: "listitem", tabIndex: 0, "aria-label": intl.formatMessage(messages.alertNotificationTypeLabel), children: [_jsxs("div", { className: e("icon"), children: [!notification.isRead && _jsx("div", { className: e("unread-status") }), isAlertNotification ? (_jsx(UiIcon, { type: "alert", size: 14, color: "complementary-6" })) : (_jsx(UiIcon, { type: "download", size: 14, color: "complementary-6" }))] }), _jsxs("div", { className: e("details"), children: [_jsxs("div", { className: e("title", { isRead: notification.isRead }), title: notificationTitle, children: [isScheduleNotification ? (_jsx(FormattedMessage, { id: "notifications.panel.download" })) : null, " ", notificationTitle] }), _jsx(NotificationContent, { isError: isError, errorTitle: errorTitle, errorMessage: errorMessage, traceId: traceId, actions: actions })] }), _jsx("div", { className: e("time"), children: _jsx(NotificationTime, { config: getDateTimeConfig(notification.createdAt) }) }), _jsx("div", { className: e("mark-as-read-button"), children: _jsx(Tooltip, { tooltip: intl.formatMessage(messages.markAsRead), children: _jsx(UiIconButton, { onClick: (e) => {
                                    e.stopPropagation();
                                    markNotificationAsRead(notification.id);
                                }, onKeyDown: (e) => {
                                    e.stopPropagation();
                                }, icon: "check", size: "small", variant: "tertiary", label: intl.formatMessage(messages.markAsRead) }) }) })] }), _jsx(Bubble, { alignPoints: [{ align: "bc tc" }], children: _jsx(FormattedMessage, { id: "notifications.panel.downloadFilesHint" }) })] }));
}
function mapToDownloadableFile(exportFile) {
    if (!exportFile.fileUri) {
        return undefined;
    }
    return {
        url: exportFile.fileUri,
        fileName: exportFile.fileName,
    };
}
function getNotificationTitle(notification) {
    if (notification.notificationType === "alertNotification") {
        return getAlertNotificationTitle(notification.details.data.alert);
    }
    else if (notification.notificationType === "scheduleNotification") {
        return notification.details.data.automation.title;
    }
    return notification.details.message;
}
function getAlertNotificationTitle(alertDescription) {
    const metric = alertDescription.metric;
    const condition = alertDescription.condition;
    const formattedThreshold = alertDescription.formattedThreshold;
    // TODO: translate (backend is currently returning English, should return translation strings)
    return `${metric} is ${condition} ${formattedThreshold}`;
}
function getNotificationErrorInfo(notification, exports) {
    if (notification.notificationType === "alertNotification" &&
        notification.details.data.alert?.status !== "SUCCESS") {
        return {
            isError: true,
            errorTitle: _jsx(FormattedMessage, { id: "notifications.panel.error.alert.title" }),
            errorMessage: notification.details.data.alert.errorMessage ?? "",
            traceId: notification.details.data.alert.traceId,
        };
    }
    if (exports.some((exportResult) => exportResult.status !== "SUCCESS")) {
        return {
            isError: true,
            errorTitle: _jsx(FormattedMessage, { id: "notifications.panel.error.schedule.title" }),
            errorMessage: exports.find((exportResult) => exportResult.status !== "SUCCESS")?.errorMessage ?? "",
            traceId: exports.find((exportResult) => exportResult.status !== "SUCCESS")?.traceId,
        };
    }
    if (notification.details.webhookMessageType === "automation-task.limit-exceeded") {
        return {
            isError: true,
            errorTitle: _jsx(FormattedMessage, { id: "notifications.panel.error.schedule.title" }),
            errorMessage: _jsx(FormattedMessage, { id: "notifications.panel.error.limitExceeded.message" }),
            traceId: undefined,
        };
    }
    return {
        isError: false,
        errorTitle: undefined,
        errorMessage: undefined,
        traceId: undefined,
    };
}
function NotificationTime({ config }) {
    if (config.isToday) {
        return _jsx(FormattedTime, { value: config.date, format: "hhmm", hour12: false });
    }
    else if (config.isYesterday) {
        return (_jsx("span", { children: _jsx(FormattedMessage, { id: "gs.date.yesterday" }) }));
    }
    return _jsx(FormattedDate, { value: config.date, format: "shortWithYear" });
}
function FileLink({ notification }) {
    return (_jsxs(BubbleHoverTrigger, { eventsOnBubble: true, children: [_jsx("a", { href: notification.details.data.automation.dashboardURL, onClick: (e) => e.stopPropagation(), onKeyDown: (e) => e.stopPropagation(), className: e("link"), children: _jsx(FormattedMessage, { id: "notifications.panel.dashboardLink", values: { dashboardTitle: notification.details.data.automation.dashboardTitle } }) }), _jsxs(Bubble, { alignPoints: [{ align: "bc tc" }], children: [" ", _jsx(FormattedMessage, { id: "notifications.panel.dashboardLinkHint" }), " "] })] }));
}
function NotificationContent({ isError, errorTitle, errorMessage, traceId, actions, }) {
    const intl = useIntl();
    if (isError) {
        return (_jsxs("div", { className: e("error"), children: [_jsx("div", { className: e("error-icon"), children: _jsx(UiIcon, { type: "crossCircle", size: 12, color: "error" }) }), _jsxs("div", { children: [errorTitle, " ", _jsx(Popup, { popup: _jsxs("div", { className: e("error-popup"), children: [errorMessage, _jsx("br", {}), _jsx(FormattedMessage, { id: "notifications.panel.error.traceId" }), ": ", traceId] }), children: ({ toggle, id }) => (_jsx(UiButton, { dataId: "notification-error", id: id, onClick: (e) => {
                                    e.stopPropagation();
                                    toggle();
                                }, onKeyDown: (e) => {
                                    e.stopPropagation();
                                }, variant: "tertiary", size: "small", label: intl.formatMessage({
                                    id: "notifications.panel.error.learnMore",
                                }) })) })] })] }));
    }
    if (!actions.length) {
        return null;
    }
    return (_jsx("div", { className: e("links"), children: actions.map((action, index) => (_jsxs(Fragment, { children: [!!index && "・", action] }, index))) }));
}
function FileExpiration({ fileExpiresAt, isExpired }) {
    if (isExpired) {
        return (_jsx("span", { children: _jsx(FormattedMessage, { id: "notifications.panel.linkHasExpired" }) }));
    }
    return (_jsxs(BubbleHoverTrigger, { eventsOnBubble: true, children: [_jsx("span", { children: _jsx(FormattedMessage, { id: "notifications.panel.expiresOn", values: {
                        date: (_jsx(FormattedDate, { value: getDateTimeConfig(fileExpiresAt).date, format: "shortWithoutYear" })),
                    } }) }), _jsxs(Bubble, { alignPoints: [{ align: "bc tc" }], children: [" ", _jsx(FormattedTime, { value: getDateTimeConfig(fileExpiresAt).date, format: "hhmm" }), " "] })] }));
}
const messages = defineMessages({
    markAsRead: {
        id: "notifications.panel.markAsRead",
    },
    alertNotificationTypeLabel: {
        id: "notifications.panel.alert.notification.type.label",
    },
    notificationExpired: {
        id: "notifications.panel.toast.warning.filesExpired",
        values: {
            strong: (text) => _jsx("strong", { children: text }),
        },
    },
});
//# sourceMappingURL=Notification.js.map