import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { FormattedMessage, useIntl } from "react-intl";
import { convertError, useBackendStrict, useWorkspaceStrict } from "@gooddata/sdk-ui";
import { ConfirmDialog } from "@gooddata/sdk-ui-kit";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { selectCanManageWorkspace } from "../../../../../model/store/permissions/permissionsSelectors.js";
import { selectCurrentUser } from "../../../../../model/store/user/userSelectors.js";
export function DeleteScheduleConfirmDialog({ scheduledEmail, returnFocusTo, onCancel, onSuccess, onError, }) {
    const effectiveBackend = useBackendStrict();
    const effectiveWorkspace = useWorkspaceStrict();
    const intl = useIntl();
    const currentUser = useDashboardSelector(selectCurrentUser);
    const canManageAutomations = useDashboardSelector(selectCanManageWorkspace);
    const handleDeleteScheduledMail = async () => {
        const alertCreatorId = scheduledEmail.createdBy?.login;
        const currentUserId = currentUser?.login;
        const isAlertCreatedByCurrentUser = !!alertCreatorId && !!currentUserId && alertCreatorId === currentUserId;
        const automationService = effectiveBackend.workspace(effectiveWorkspace).automations();
        // If schedule 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 {
            await deleteMethod(scheduledEmail.id);
            onSuccess?.();
        }
        catch (err) {
            onError?.(convertError(err));
        }
    };
    return (_jsx(ConfirmDialog, { displayCloseButton: true, isPositive: false, headline: intl.formatMessage({ id: "dialogs.schedule.management.delete.dialog" }), cancelButtonText: intl.formatMessage({ id: "cancel" }), submitButtonText: intl.formatMessage({ id: "delete" }), onSubmit: () => {
            void handleDeleteScheduledMail();
        }, onClose: onCancel, onCancel: onCancel, returnFocusTo: returnFocusTo, className: "gd-notifications-channel-delete-dialog s-scheduled-email-delete-dialog", containerClassName: "gd-notifications-channel-delete-dialog-overlay", children: _jsx("span", { className: "s-notifications-channel-delete-dialog-content", children: _jsx(FormattedMessage, { id: "dialogs.schedule.management.delete.dialog.confirm", values: {
                    b: (chunks) => (_jsxs("span", { className: "gd-notifications-channel-delete-dialog-text", children: [chunks, " ",
                            _jsx("strong", { children: scheduledEmail.title })
                        ] })),
                } }) }) }));
}
