const rootStyles = getComputedStyle(document.documentElement);
const background = rootStyles.getPropertyValue('--swal-bg')?.trim();
const color = rootStyles.getPropertyValue('--swal-text-color')?.trim();

function showDeleteConfirmation({
                                    itemUuid,
                                    itemName,
                                    apiUrl,
                                    row,
                                    deleteAction,
                                    title = "Are you sure?",
                                    text = "You won't be able to revert this!",
                                    icon = "question",
                                    confirmButtonText = "Yes, delete",
                                    cancelButtonText = "Cancel!",
                                    background = getComputedStyle(document.documentElement).getPropertyValue('--swal-bg')?.trim(),
                                    color = getComputedStyle(document.documentElement).getPropertyValue('--swal-text-color')?.trim(),
                                    customClass = {
                                        confirmButton: "btn btn-danger mx-2",
                                        cancelButton: "btn btn-secondary"
                                    },
                                    responseSuccessTitle = '',
                                    responseSuccessText = '',
                                    responseSuccessBtnText = '',
                                    responseErrorTitle = '',
                                    responseErrorText = '',
                                    cancelConfirmTitle = '',
                                    cancelConfirmText = '',
                                    cancelConfirmBtnText = ''
                                }) {
    Swal.fire({
        title: title,
        text: text,
        icon: icon,
        background: background,
        color: color,
        showCancelButton: true,
        confirmButtonText: confirmButtonText,
        cancelButtonText: cancelButtonText,
        customClass: customClass,
        buttonsStyling: false,
    }).then((result) => {
        if (result.isConfirmed) {
            // Make the POST request to delete the item
            $.post(apiUrl, {
                [itemName]: itemUuid,
                "X-HTTP-Method-Override": "DELETE"
            })
                .done(function (response) {

                    if (!(typeof deleteAction === "string" && deleteAction.startsWith("url:"))) { // do not fire the swal if there will be a redirect
                        Swal.fire({
                            background: background,
                            color: color,
                            title: responseSuccessTitle || "Deleted!",
                            text: response.message || responseSuccessText || "Your item has been deleted.",
                            confirmButtonText: responseSuccessBtnText,
                            icon: "success",
                            customClass: {
                                confirmButton: "btn btn-success",
                            },
                            buttonsStyling: true,
                        });
                    }

                    if (typeof deleteAction === "string" && deleteAction.startsWith("url:")) {
                        window.location.href = deleteAction.replace("url:", "").trim();
                    } else if (!deleteAction || deleteAction === "false") {
                        row.fadeOut(500, function () {
                            $(this).remove();
                        });
                    } else {
                        try {
                            let actions = typeof deleteAction === "string" ? JSON.parse(deleteAction) : deleteAction;
                            for (const [elementId, action] of Object.entries(actions)) {
                                let $element = $("#" + elementId);

                                if (action === "show") {
                                    $element.removeClass("d-none").fadeIn(500);
                                } else if (action === "hide") {
                                    $element.fadeOut(0).addClass("d-none");
                                }
                            }
                        } catch (error) {
                            console.error("Error parsing deleteAction JSON:", error);
                        }
                    }
                })
                .fail(function (jqXHR) {
                    // Parse the error response
                    let response = jqXHR.responseJSON || {};
                    Swal.fire({
                        background: background,
                        color: color,
                        title: responseErrorTitle || "Error",
                        text: response.message || responseErrorText || "An error occurred. Please contact support.",
                        icon: "error",
                        customClass: {
                            confirmButton: "btn btn-danger",
                        },
                        buttonsStyling: false,
                    });
                });
        } else if (result.dismiss === Swal.DismissReason.cancel) {
            Swal.fire({
                background: background,
                color: color,
                title: cancelConfirmTitle,
                text: cancelConfirmText,
                confirmButtonText: cancelConfirmBtnText,
                icon: "info",
                customClass: {
                    confirmButton: "btn btn-black",
                },
                buttonsStyling: false,
            });
        }
    });
}

// Attach event listener
$(document).on('click', '.delete-btn', function (e) {
    e.preventDefault(); // Prevent default link behavior

    const itemUuid = $(this).data('item-uuid');
    const itemName = $(this).data('item-name')
    const apiUrl = $(this).data('api-url');
    const deleteAction = $(this).data('delete-action') || false;
    const row = $(this).closest('tr');

    const deleteOptions = {
        itemUuid: itemUuid,
        itemName: itemName,
        apiUrl: apiUrl,
        row: row,
        deleteAction: deleteAction,
        title: __('action_confirm'),
        text: __('action_confirm_text'),
        icon: "question",
        confirmButtonText: __('action_confirm_button'),
        cancelButtonText: __('action_cancel_button'),
        responseSuccessTitle: __('action_success_title'),
        responseSuccessText: __('action_success_text'),
        responseSuccessBtnText: __('close'),
        responseErrorTitle: __('action_error_title'),
        responseErrorText: __('action_error_text'),
        cancelConfirmTitle: __('action_cancel_confirm_title'),
        cancelConfirmText: __('action_cancel_confirm_text'),
        cancelConfirmBtnText: __('close'),
    };

    showDeleteConfirmation(deleteOptions);
});