document.addEventListener("DOMContentLoaded", function () {
    initializeModalButtons();
    //initializeGlobalAjaxSpinner();
});

const initializedButtons = new WeakSet();

function initializeModalButtons() {
    document.querySelectorAll('[data-bs-toggle="modal"]').forEach(function (button) {
        if (!initializedButtons.has(button)) {
            button.addEventListener('click', function (event) {
                event.preventDefault();
                modelbuttonhit(button);
            });
            initializedButtons.add(button);
        }
    });
}

function addFormEventListeners(modalId) {
    var form = document.querySelector(modalId + ' form');

    if (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();

            // Use jQuery validation to check form validity
            $.validator.unobtrusive.parse(form);

            // Validate the form using jQuery Unobtrusive Validation
            if (!$(form).valid()) {
                toastr.error('Please correct the errors in the form.');
                return;
            }

            var action = form.getAttribute('action');
            var method = form.getAttribute('method');
            var formData = new FormData(form);
            showSpinner();
            fetch(action, {
                method: method,
                body: formData
            }).then(response => response.text())
                .then(data => {
                    hideSpinner();
                    try {                      
                        var json = JSON.parse(data);
                        if (json.success) {
                            bootstrap.Modal.getInstance(document.querySelector(modalId)).hide();
                            toastr.success('Operation completed successfully.');

                            if (json.refreshForm && document.getElementById(json.refreshForm)) {
                                const form = document.getElementById(json.refreshForm);
                                // Create a synthetic event to pass to handleFormSubmission
                                const syntheticEvent = new Event('submit', { bubbles: true, cancelable: true });
                                form.addEventListener('submit', handleFormSubmission); // Attach handler to form
                                form.dispatchEvent(syntheticEvent); // Trigger synthetic event

                            } else if (json.dataUrl && typeof updateTable === 'function') {
                                updateTable(json.dataUrl);
                            }
                            else if (json.redirectUrl) {
                                window.location.href = json.redirectUrl;
                            }
                            else if (json.reloadPage) {
                                window.location.reload();
                            }
                            else if (json.callonmodalSuccess) {
                                if (typeof callonmodalSuccess === 'function') {
                                    // Call the new function if it exists
                                    callonmodalSuccess();
                                }
                            }

                        } else {
                            toastr.error(json.message || 'An error occurred. Please try again.');
                            if (typeof callonmodalError === 'function') {
                                // Call the new function if it exists
                                callonmodalError();
                            }
                        }
                    } catch (e) {
                        // If JSON parsing fails, assume it's HTML and update modal content
                        document.querySelector(modalId + ' .modal-content').innerHTML = data;

                        addFormEventListeners(modalId);
                        // Re-initialize validation for the new content
                        $.validator.unobtrusive.parse(document.querySelector(modalId + ' form'));
                        if (isJsonString(document.querySelector(modalId + ' .modal-content').innerHTML)) {
                            toastr.error('An error occurred. Please correct the form and try again.');
                        }
                        if (typeof callonmodalError === 'function') {
                            // Call the new function if it exists
                            callonmodalError();
                        }

                    }
                })
                .catch(error => {
                    hideSpinner();
                    console.error('Error submitting form:', error);
                    toastr.error('An error occurred while submitting the form. Please try again.');
                    if (typeof callonmodalError === 'function') {
                        // Call the new function if it exists
                        callonmodalError();
                    }
                });
        });
    }
}
function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
function updateTable(tableUrl) {
    showSpinner();
    fetch(tableUrl)
        .then(response => response.text())
        .then(data => {
            hideSpinner();
            document.querySelector('#table-body').innerHTML = data;
            initializeModalButtons();
            toastr.success('Table updated successfully.');
        })
        .catch(error => {
            hideSpinner();
            console.error('Error updating table:', error);
            toastr.error('An error occurred while updating the table. Please try again.');
        });
}

function modelbuttonhit(button) {
    var url = button.getAttribute('data-bs-url');
    var modalId = button.getAttribute('data-bs-target');
    var modalSize = button.getAttribute('data-bs-size');
    showSpinner();
    fetch(url)
        .then(response => {
           /* hideSpinner();*/
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.text();
        })
        .then(data => {
            var modalElement = document.querySelector(modalId);
            var modalContent = modalElement.querySelector('.modal-content');
            modalContent.innerHTML = data;

            var modalDialog = modalElement.querySelector('.modal-dialog');
            modalDialog.classList.remove('modal-sm', 'modal-lg', 'modal-xl');
            if (modalSize) {
                modalDialog.classList.add(modalSize);
            }

            var modal = new bootstrap.Modal(modalElement);
            modal.show();
            addFormEventListeners(modalId);            

            if (typeof callonmodalLoad === 'function') {
                // Call the new function if it exists
                callonmodalLoad();
            }

            modalElement.addEventListener('hidden.bs.modal', function () {
                modalContent.innerHTML = '';
                document.body.classList.remove('modal-open');
                var backdrop = document.querySelector('.modal-backdrop');
                if (backdrop) {
                    backdrop.remove();
                }
            });

            const selectedRadio = document.querySelector('input[name="tab"]:checked');
            if (selectedRadio) {
                selectedRadio.onchange();  // Trigger the onchange event
            }
            else {
                hideSpinner();
            }
            
        })
        .catch(error => {
            hideSpinner();
            console.error('Error fetching modal content:', error);
            if (isJsonString(document.querySelector(modalId + ' .modal-content').innerHTML)) {
                toastr.error('An error occurred while loading the modal content. Please try again.');
            }
        });
        
}

//function initializeGlobalAjaxSpinner() {
//    $(document).ajaxStart(function () {
//        showSpinner();
//    }).ajaxStop(function () {
//        hideSpinner();
//    });
//}
