import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2022-2026 GoodData Corporation
import { useCallback, useEffect, useMemo, useState } from "react";
import cx from "classnames";
import { isInsightWidget, objRefToString, } from "@gooddata/sdk-model";
import { fillMissingTitles, useBackendStrict, useWorkspaceStrict } from "@gooddata/sdk-ui";
import { OverlayController, OverlayControllerProvider, ScrollablePanel, useToastMessage, } from "@gooddata/sdk-ui-kit";
import { simplifyText } from "@gooddata/util";
import { useDashboardSelector } from "../../../../model/react/DashboardStoreProvider.js";
import { useDashboardAlerts } from "../../../../model/react/useDashboardAlerting/useDashboardAlerts.js";
import { DEFAULT_MAX_AUTOMATIONS } from "../../../../model/react/useDashboardAutomations/constants.js";
import { useDashboardAutomations } from "../../../../model/react/useDashboardAutomations/useDashboardAutomations.js";
import { selectAllAutomationsCount, selectAutomationsIsLoading, selectDashboardUserAutomationAlertsInContext, } from "../../../../model/store/automations/automationsSelectors.js";
import { selectCatalogDateDatasets } from "../../../../model/store/catalog/catalogSelectors.js";
import { selectEnableComparisonInAlerting, selectLocale, } from "../../../../model/store/config/configSelectors.js";
import { selectEntitlementMaxAutomations, selectEntitlementUnlimitedAutomations, } from "../../../../model/store/entitlements/entitlementsSelectors.js";
import { selectInsightByWidgetRef } from "../../../../model/store/insights/insightsSelectors.js";
import { selectCanCreateAutomation, selectCanManageWorkspace, } from "../../../../model/store/permissions/permissionsSelectors.js";
import { selectExecutionTimestamp } from "../../../../model/store/ui/uiSelectors.js";
import { selectCurrentUser } from "../../../../model/store/user/userSelectors.js";
import { AlertDeleteDialog } from "../../../automations/alerting/DefaultAlertingDialog/components/AlertDeleteDialog.js";
import { messages } from "../../../automations/alerting/DefaultAlertingDialog/messages.js";
import { getSupportedInsightMeasuresByInsight } from "../../../automations/alerting/DefaultAlertingDialog/utils/items.js";
import { DASHBOARD_HEADER_OVERLAYS_Z_INDEX } from "../../../constants/zIndex.js";
import { AlertsList } from "./InsightAlertConfig/AlertsList.js";
import { useSaveAlertToBackend } from "./InsightAlertConfig/hooks/useSaveAlertToBackend.js";
import { NoAvailableMeasures } from "./InsightAlertConfig/NoAvailableAlerts.js";
const overlayController = OverlayController.getInstance(DASHBOARD_HEADER_OVERLAYS_Z_INDEX);
export function InsightAlertsNew({ widget, onClose, onGoBack }) {
    const insight = useDashboardSelector(selectInsightByWidgetRef(widget.ref));
    const currentUser = useDashboardSelector(selectCurrentUser);
    const effectiveBackend = useBackendStrict();
    const effectiveWorkspace = useWorkspaceStrict();
    const canManageAutomations = useDashboardSelector(selectCanManageWorkspace);
    const locale = useDashboardSelector(selectLocale);
    const catalogDateDatasets = useDashboardSelector(selectCatalogDateDatasets);
    const canManageComparison = useDashboardSelector(selectEnableComparisonInAlerting);
    const automationsLoading = useDashboardSelector(selectAutomationsIsLoading);
    const automationsCount = useDashboardSelector(selectAllAutomationsCount);
    const maxAutomationsEntitlement = useDashboardSelector(selectEntitlementMaxAutomations);
    const unlimitedAutomationsEntitlement = useDashboardSelector(selectEntitlementUnlimitedAutomations);
    const isExecutionTimestampMode = !!useDashboardSelector(selectExecutionTimestamp);
    const canCreateAutomation = useDashboardSelector(selectCanCreateAutomation);
    const alerts = useDashboardSelector(selectDashboardUserAutomationAlertsInContext(widget.localIdentifier));
    const [isDeleteInProgress, setIsDeleteInProgress] = useState(false);
    const [alertToDelete, setAlertToDelete] = useState(null);
    const widgetRefSuffix = isInsightWidget(widget) ? simplifyText(objRefToString(widget.ref)) : "";
    const classes = cx("gd-alerts-configuration-panel", "configuration-scrollable-panel", "s-configuration-scrollable-panel", `s-visualization-${widgetRefSuffix}`);
    const { onAlertingOpen } = useDashboardAlerts();
    const { refreshAutomations } = useDashboardAutomations();
    const { addSuccess, addError } = useToastMessage();
    const { handlePauseAlert, handleResumeAlert, isSavingAlert } = useSaveAlertToBackend({
        onPauseSuccess: () => {
            refreshAutomations();
            addSuccess(messages.alertPauseSuccess);
        },
        onPauseError: () => {
            addError(messages.alertSaveError);
        },
        onResumeSuccess: () => {
            refreshAutomations();
            addSuccess(messages.alertResumeSuccess);
        },
        onResumeError: () => {
            addError(messages.alertSaveError);
        },
    });
    const initiateAlertCreation = () => {
        onAlertingOpen(widget);
    };
    const initiateAlertEditing = (alert) => {
        onAlertingOpen(widget, alert);
    };
    const pauseExistingAlert = (alert) => {
        const alertToPause = {
            ...alert,
            alert: { ...alert.alert, trigger: { ...alert.alert?.trigger, state: "PAUSED" } },
        };
        handlePauseAlert(alertToPause);
    };
    const resumeExistingAlert = (alert) => {
        const alertToResume = {
            ...alert,
            alert: { ...alert.alert, trigger: { ...alert.alert?.trigger, state: "ACTIVE" } },
        };
        handleResumeAlert(alertToResume);
    };
    const startDeletingAlert = useCallback((alert) => {
        setAlertToDelete(alert);
    }, []);
    const cancelDeletingAlert = useCallback(() => {
        setAlertToDelete(null);
    }, []);
    const deleteExistingAlert = useCallback(async () => {
        if (!alertToDelete) {
            return;
        }
        setIsDeleteInProgress(true);
        const alertCreatorId = alertToDelete.createdBy?.login;
        const currentUserId = currentUser?.login;
        const isAlertCreatedByCurrentUser = !!alertCreatorId && !!currentUserId && alertCreatorId === currentUserId;
        const automationService = effectiveBackend.workspace(effectiveWorkspace).automations();
        // If alert is created by current user, or user has permissions to manage automations, delete it, otherwise unsubscribe
        const deleteMethod = canManageAutomations || isAlertCreatedByCurrentUser
            ? automationService.deleteAutomation.bind(automationService)
            : automationService.unsubscribeAutomation.bind(automationService);
        try {
            setAlertToDelete(null);
            await deleteMethod(alertToDelete.id);
            addSuccess(messages.alertDeleteSuccess);
            setIsDeleteInProgress(false);
            refreshAutomations();
        }
        catch {
            addError(messages.alertDeleteError);
            setIsDeleteInProgress(false);
        }
    }, [
        addError,
        addSuccess,
        alertToDelete,
        canManageAutomations,
        currentUser?.login,
        effectiveBackend,
        effectiveWorkspace,
        refreshAutomations,
    ]);
    const maxAutomations = parseInt(maxAutomationsEntitlement?.value ?? DEFAULT_MAX_AUTOMATIONS, 10);
    const maxAutomationsReached = automationsCount >= maxAutomations && !unlimitedAutomationsEntitlement;
    const [effectiveInsight, setEffectiveInsight] = useState(insight);
    useEffect(() => {
        if (insight) {
            void fillMissingTitles(insight, locale, 9999).then(setEffectiveInsight);
        }
    }, [insight, locale]);
    const supportedMeasures = useMemo(() => getSupportedInsightMeasuresByInsight(effectiveInsight, catalogDateDatasets, canManageComparison), [effectiveInsight, catalogDateDatasets, canManageComparison]);
    return (_jsx(ScrollablePanel, { className: classes, children: _jsxs(OverlayControllerProvider, { overlayController: overlayController, children: [automationsLoading || supportedMeasures.length > 0 ? (_jsx(AlertsList, { isLoading: automationsLoading || isSavingAlert || isDeleteInProgress, alerts: alerts, onCreateAlert: initiateAlertCreation, onEditAlert: initiateAlertEditing, onPauseAlert: pauseExistingAlert, onResumeAlert: resumeExistingAlert, onDeleteAlert: startDeletingAlert, onClose: onClose, onGoBack: onGoBack, maxAutomationsReached: maxAutomationsReached, canCreateAutomation: canCreateAutomation, isExecutionTimestampMode: isExecutionTimestampMode })) : (_jsx(NoAvailableMeasures, { onClose: onClose, onBack: onGoBack })), alertToDelete ? (_jsx(AlertDeleteDialog, { onCancel: cancelDeletingAlert, onDelete: () => {
                        void deleteExistingAlert();
                    }, title: alertToDelete.title })) : null] }) }));
}
