import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { FormattedMessage, defineMessages, useIntl } from "react-intl";
import { Bubble, BubbleHoverTrigger, Button, Input, Message, } from "@gooddata/sdk-ui-kit";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { selectInsightByWidgetRef } from "../../../../../model/store/insights/insightsSelectors.js";
import { selectWidgets } from "../../../../../model/store/tabs/layout/layoutSelectors.js";
import { AlertAttributeSelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertAttributeSelect.js";
import { AlertComparisonOperatorSelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertComparisonOperatorSelect.js";
import { AlertComparisonPeriodSelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertComparisonPeriodSelect.js";
import { AlertDestinationSelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertDestinationSelect.js";
import { AlertGranularitySelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertGranularitySelect.js";
import { AlertMeasureSelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertMeasureSelect.js";
import { AlertSensitivitySelect } from "../../../../automations/alerting/DefaultAlertingDialog/components/AlertSensitivitySelect.js";
import { useAlertValidation, } from "../../../../automations/alerting/DefaultAlertingDialog/hooks/useAlertValidation.js";
import { useAttributeValuesFromExecResults } from "../../../../automations/alerting/DefaultAlertingDialog/hooks/useAttributeValuesFromExecResults.js";
import { useThresholdValue } from "../../../../automations/alerting/DefaultAlertingDialog/hooks/useThresholdValue.js";
import { getAlertAiOperator, getAlertAttribute, getAlertCompareOperator, getAlertComparison, getAlertFilters, getAlertGranularity, getAlertMeasure, getAlertRelativeOperator, getAlertSensitivity, getValueSuffix, } from "../../../../automations/alerting/DefaultAlertingDialog/utils/getters.js";
import { translateGranularity } from "../../../../automations/alerting/DefaultAlertingDialog/utils/granularity.js";
import { isAnomalyDetection, isChangeOrDifferenceOperator, } from "../../../../automations/alerting/DefaultAlertingDialog/utils/guards.js";
import { RecipientsSelect } from "../../../../automations/scheduledEmail/DefaultScheduledEmailDialog/components/RecipientsSelect/RecipientsSelect.js";
import { DashboardInsightSubmenuContainer } from "../../../insightMenu/DefaultDashboardInsightMenu/DashboardInsightMenu/DashboardInsightSubmenuContainer.js";
import { AlertTitle } from "./AlertTitle.js";
import { EditAlertConfiguration } from "./EditAlertConfiguration.js";
import { useEditAlert } from "./hooks/useEditAlert.js";
const TOOLTIP_ALIGN_POINTS = [{ align: "cl cr" }, { align: "cr cl" }];
const messages = defineMessages({
    invalidDefault: {
        id: "insightAlert.config.invalid",
    },
    invalidWidget: {
        id: "insightAlert.config.invalidWidget",
    },
});
const invalidMessagesObj = {
    missingMetric: messages.invalidDefault,
    missingWidget: messages.invalidWidget,
};
export function EditAlert({ alert, execResult, isNewAlert, hasAlerts, destinations, users, attributes, measures, onClose, onCancel, onCreate, onUpdate, maxAutomationsReached = false, maxAutomationsRecipients, overlayPositionType, measureFormatMap, catalogAttributes, catalogDateDatasets, canManageAttributes, canManageComparison, separators, isExecutionTimestampMode, }) {
    const { defaultUser, viewMode, updatedAlert, canSubmit, allowExternalRecipients, allowOnlyLoggedUserRecipients, warningMessage, enableAnomalyDetectionAlert, allowHourlyRecurrence, 
    //
    changeAnomalyDetection, changeComparisonOperator, changeRelativeOperator, changeMeasure, changeAttribute, changeTitle, changeValue, changeDestination, changeComparisonType, changeRecipients, changeSensitivity, changeGranularity, 
    //
    configureAlert, saveAlertConfiguration, cancelAlertConfiguration, 
    //
    createAlert, updateAlert, } = useEditAlert({
        metrics: measures,
        separators,
        attributes,
        alert,
        onCreate,
        onUpdate,
        measureFormatMap,
        catalogAttributes,
        catalogDateDatasets,
        destinations,
    });
    const intl = useIntl();
    const disableCreateButtonDueToLimits = isNewAlert && maxAutomationsReached;
    const selectedMeasure = getAlertMeasure(measures, updatedAlert.alert);
    const selectedComparator = getAlertComparison(selectedMeasure, updatedAlert.alert);
    const [selectedAttribute, selectedValue] = getAlertAttribute(attributes, updatedAlert);
    const filters = getAlertFilters(updatedAlert);
    const selectedComparisonOperator = getAlertCompareOperator(updatedAlert.alert);
    const selectedRelativeOperator = getAlertRelativeOperator(updatedAlert.alert);
    const selectedAiOperator = getAlertAiOperator(updatedAlert.alert);
    const selectedSensitivity = getAlertSensitivity(updatedAlert.alert);
    const selectedGranularity = getAlertGranularity(updatedAlert.alert);
    const widgetLocalId = alert?.metadata?.widget;
    const allWidgets = useDashboardSelector(selectWidgets);
    const alertWidget = widgetLocalId
        ? allWidgets.find((w) => w.localIdentifier === widgetLocalId)
        : undefined;
    const alertInsight = useDashboardSelector(selectInsightByWidgetRef(alertWidget?.ref));
    const { isValid, invalidityReason } = useAlertValidation(alert, alertWidget, alertInsight, catalogDateDatasets, isNewAlert, canManageComparison);
    const showFilterInfo = filters.length > 0 || Boolean(selectedComparator?.granularity);
    const { isResultLoading, getAttributeValues, getMetricValue } = useAttributeValuesFromExecResults(execResult);
    const { value, onChange, onBlur } = useThresholdValue(changeValue, getMetricValue, isNewAlert, updatedAlert.alert, selectedRelativeOperator, selectedMeasure, selectedAttribute, selectedValue);
    return viewMode === "edit" ? (_jsx(DashboardInsightSubmenuContainer, { title: isNewAlert
            ? intl.formatMessage({ id: "insightAlert.config.createAlert" })
            : intl.formatMessage({ id: "insightAlert.config.editAlert" }), onClose: onClose, onBack: hasAlerts ? onCancel : undefined, children: _jsxs("div", { className: "gd-edit-alert", children: [
                _jsxs("div", { className: "gd-edit-alert__form", children: [
                        _jsxs("div", { className: "gd-edit-alert__form-content", children: [
                                _jsx("label", { htmlFor: "alert.measure", className: "gd-edit-alert__measure-label", children: _jsx(FormattedMessage, { id: "insightAlert.config.when" }) }), _jsx(AlertMeasureSelect, { selectedMeasure: selectedMeasure, onMeasureChange: changeMeasure, measures: measures, overlayPositionType: overlayPositionType, id: "alert.measure" }), Boolean(canManageAttributes) && (_jsx(_Fragment, { children: _jsx(AlertAttributeSelect, { id: "alert.attribute", selectedAttribute: selectedAttribute, selectedValue: selectedValue, onAttributeChange: changeAttribute, attributes: attributes, catalogAttributes: catalogAttributes, catalogDateDatasets: catalogDateDatasets, getAttributeValues: getAttributeValues, isResultLoading: isResultLoading, showLabel: true, closeOnParentScroll: true }) })), showFilterInfo ? (_jsxs("div", { className: "gd-edit-alert__measure-info", children: [Boolean(selectedComparator?.granularity) && (_jsx(FormattedMessage, { tagName: "span", id: "insightAlert.config.for.filter", values: {
                                                granularity: [
                                                    intl.formatMessage({ id: "granularity.this_keyword" }),
                                                    translateGranularity(intl, selectedComparator?.granularity),
                                                ].join(" "),
                                            } })), filters.length > 0 && selectedComparator?.granularity ? (_jsx(FormattedMessage, { tagName: "span", id: "insightAlert.config.and" })) : null, filters.length > 0 && (_jsxs(_Fragment, { children: [
                                                _jsx(FormattedMessage, { tagName: "span", id: "insightAlert.config.filters", values: {
                                                        n: filters.length,
                                                    } }), _jsx("div", { role: "item-info", className: "gd-list-item-bubble", children: _jsxs(BubbleHoverTrigger, { tagName: "div", showDelay: 200, hideDelay: 0, eventsOnBubble: false, children: [
                                                            _jsx("div", { className: "inlineBubbleHelp" }), _jsx(Bubble, { className: "bubble-primary", alignPoints: [{ align: "cr cl" }, { align: "cl cr" }], arrowOffsets: { "cr cl": [15, 0] }, children: _jsx(FormattedMessage, { id: "insightAlert.config.filters.info", values: {
                                                                        spacer: (_jsx("div", { className: "gd-alert-comparison-operator-tooltip-spacer" })),
                                                                    } }) })
                                                        ] }) })
                                            ] }))] })) : null, _jsx(AlertComparisonOperatorSelect, { id: "alert.comparisonOperator", measure: selectedMeasure, enableAnomalyDetectionAlert: enableAnomalyDetectionAlert, selectedAiOperator: selectedAiOperator, onAnomalyDetectionChange: changeAnomalyDetection, selectedComparisonOperator: selectedComparisonOperator, selectedRelativeOperator: selectedRelativeOperator, onComparisonOperatorChange: changeComparisonOperator, onRelativeOperatorChange: changeRelativeOperator, overlayPositionType: overlayPositionType }), !isAnomalyDetection(updatedAlert?.alert) &&
                                    (() => {
                                        const valueSuffix = getValueSuffix(updatedAlert.alert);
                                        const suffixAriaLabel = valueSuffix === "%"
                                            ? intl.formatMessage({ id: "input.unit.percent" })
                                            : valueSuffix;
                                        return (_jsx(Input, { className: "gd-edit-alert__value-input s-alert-value-input", isSmall: true, autofocus: true, value: value, onChange: onChange, onBlur: onBlur, type: "number", suffix: valueSuffix, accessibilityConfig: {
                                                ariaLabel: intl.formatMessage({
                                                    id: "insightAlert.config.accessbility.input",
                                                }),
                                                suffixAriaLabel,
                                            } }));
                                    })(), !updatedAlert || !isChangeOrDifferenceOperator(updatedAlert.alert) ? null : (_jsxs("div", { style: { marginTop: "1rem" }, children: [
                                        _jsx("label", { htmlFor: "alert.comparison", children: _jsx(FormattedMessage, { id: "insightAlert.config.comparison" }) }), _jsx(AlertComparisonPeriodSelect, { id: "alert.comparison", measure: selectedMeasure, alert: updatedAlert, selectedComparison: selectedComparator?.comparator, selectedGranularity: selectedComparator?.granularity, onComparisonChange: (comparisonType, granularity) => {
                                                changeComparisonType(selectedMeasure, selectedRelativeOperator, comparisonType, granularity);
                                            }, overlayPositionType: overlayPositionType, canManageComparison: canManageComparison })
                                    ] })), !updatedAlert || !isAnomalyDetection(updatedAlert.alert) ? null : (_jsxs(_Fragment, { children: [
                                        _jsxs("div", { style: { marginTop: "1rem" }, children: [
                                                _jsx("label", { htmlFor: "alert.sensitivity", children: _jsx(FormattedMessage, { id: "insightAlert.config.sensitivity" }) }), _jsx(AlertSensitivitySelect, { id: "alert.sensitivity", selectedSensitivity: selectedSensitivity, onSensitivityChange: changeSensitivity, overlayPositionType: overlayPositionType })
                                            ] }), _jsxs("div", { children: [
                                                _jsx("label", { htmlFor: "alert.granularity", children: _jsx(FormattedMessage, { id: "insightAlert.config.granularity" }) }), _jsx(AlertGranularitySelect, { id: "alert.granularity", allowHourlyRecurrence: allowHourlyRecurrence, selectedGranularity: selectedGranularity, onGranularityChange: (granularity) => {
                                                        changeGranularity(selectedMeasure, granularity);
                                                    }, overlayPositionType: overlayPositionType })
                                            ] })
                                    ] })), destinations.length > 1 && (_jsxs("div", { style: { marginTop: "1rem" }, children: [
                                        _jsx("label", { htmlFor: "alert.destination", className: "gd-edit-alert__destination-label", children: _jsx(FormattedMessage, { id: "insightAlert.config.action" }) }), _jsx(AlertDestinationSelect, { id: "alert.destination", selectedDestination: updatedAlert.notificationChannel, onDestinationChange: changeDestination, destinations: destinations, overlayPositionType: overlayPositionType })
                                    ] })), _jsx(RecipientsSelect, { id: "alert.recipients", loggedUser: defaultUser, users: users, value: updatedAlert.recipients ?? [], originalValue: alert.recipients || [], onChange: changeRecipients, allowEmptySelection: true, allowOnlyLoggedUserRecipients: allowOnlyLoggedUserRecipients, allowExternalRecipients: allowExternalRecipients, maxRecipients: maxAutomationsRecipients, className: "gd-edit-alert__recipients", notificationChannels: destinations, notificationChannelId: updatedAlert.notificationChannel }), _jsx("label", { htmlFor: "alert.title", className: "gd-edit-alert__title-label", children: _jsx(FormattedMessage, { id: "insightAlert.config.name" }) }), _jsx(AlertTitle, { id: "alert.title", measures: measures, alert: updatedAlert, separators: separators, onChange: (e) => {
                                        changeTitle(e === "" ? undefined : String(e));
                                    } })
                            ] }), warningMessage ? _jsx(Message, { type: "warning", children: warningMessage }) : null, isValid ? null : (_jsx(Message, { type: "error", children: _jsx(FormattedMessage, { id: invalidMessagesObj[invalidityReason].id }) }))] }), _jsxs("div", { className: "gd-edit-alert__buttons", children: [
                        _jsx(Button, { className: "gd-edit-alert__configuration-button gd-button-link gd-button-icon-only gd-icon-settings gd-button-small s-alert-configuration", onClick: configureAlert }), _jsxs("div", { children: [
                                _jsx(Button, { variant: "secondary", size: "small", onClick: () => {
                                        onCancel();
                                    }, children: _jsx(FormattedMessage, { id: "cancel" }) }), _jsxs(BubbleHoverTrigger, { hideDelay: 0, showDelay: 0, children: [
                                        _jsx(Button, { intent: "action", size: "small", disabled: !canSubmit || disableCreateButtonDueToLimits || isExecutionTimestampMode, onClick: isNewAlert ? createAlert : updateAlert, className: "gd-button-left-margin", children: isNewAlert
                                                ? intl.formatMessage({ id: "create" })
                                                : intl.formatMessage({ id: "save" }) }), disableCreateButtonDueToLimits ? (_jsx(Bubble, { alignPoints: TOOLTIP_ALIGN_POINTS, children: _jsx(FormattedMessage, { id: "insightAlert.maxAlertsReached" }) })) : null, isExecutionTimestampMode ? (_jsx(Bubble, { alignPoints: TOOLTIP_ALIGN_POINTS, children: _jsx(FormattedMessage, { id: "insightAlert.executionTimestampMode" }) })) : null] })
                            ] })
                    ] })
            ] }) })) : (_jsx(DashboardInsightSubmenuContainer, { title: intl.formatMessage({ id: "insightAlert.config.title" }), onClose: onClose, onBack: cancelAlertConfiguration, children: _jsx(EditAlertConfiguration, { alert: updatedAlert, onUpdate: saveAlertConfiguration, onCancel: cancelAlertConfiguration, overlayPositionType: overlayPositionType }) }));
}
