var listFormDiv;
document.addEventListener('DOMContentLoaded', function () {
    hideSpinner();
    listFormDiv = document.querySelector('.list-form');

    if (listFormDiv) {
        attachFormSubmitHandler();       
    }
});

function attachFormSubmitHandler() {
    const form = listFormDiv.querySelector('form#mainForm');

    if (form) {
        form.addEventListener('submit', handleFormSubmission);
    }
}

function handleFormSubmission(event) {
    event.preventDefault(); // Prevent the default form submission
    const form = event.target;
    const action = form.getAttribute('action');
    const method = form.getAttribute('method');
    const formData = new FormData(form);

    // Show spinner
    showSpinner();

    fetch(action, {
        method: method,
        body: formData
    })
        .then(response => response.text())
        .then(data => {
            //hideSpinner(); // Hide spinner after receiving response

            // Update parent div content with new HTML
            listFormDiv.innerHTML = data;

            // Reattach event listener to the new form element
            attachFormSubmitHandler();
            initializeModalButtons();
            //toastr.success('Form submitted successfully.');
        })
        .catch(error => {
            //hideSpinner();
            console.error('Error submitting form:', error);
            toastr.error('An error occurred while submitting the form. Please try again.');
        }).finally(() => {
            hideSpinner();
        });
}

// Function to trigger form submission with fetch
function triggerFormSubmission() {
    const form = document.getElementById('mainForm');
    if (form) {
        // Manually call handleFormSubmission
        const event = new Event('submit', { bubbles: true, cancelable: true });
        form.dispatchEvent(event);
    }
}

// Function to handle sorting
function setSort(column) {
    var sortColumn = document.querySelector('input[name="SortColumn"]').value;
    var sortOrder = document.querySelector('input[name="SortOrder"]').value;

    if (sortColumn === column) {
        sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        sortColumn = column;
        sortOrder = 'asc';
    }

    document.querySelector('input[name="SortColumn"]').value = sortColumn;
    document.querySelector('input[name="SortOrder"]').value = sortOrder;
    document.querySelector('input[name="PageNumber"]').value = 1;

    // Use fetch to submit the form
    triggerFormSubmission();
}

// Function to handle pagination
function setPage(pageNumber) {
    showSpinner();
    document.querySelector('input[name="PageNumber"]').value = pageNumber;

    // Use fetch to submit the form
    triggerFormSubmission();
}

// Function to handle page size change
function setPageSize(pageSize) {
    document.querySelector('input[name="PageSize"]').value = pageSize;
    document.querySelector('input[name="PageNumber"]').value = 1;
    // Use fetch to submit the form
    triggerFormSubmission();
}

// Function to apply filters
function submitFilters() {
    document.querySelectorAll('input[type="text"]').forEach(function (input) {
        var hiddenInput = document.querySelector(`input[name="Filters[${input.name.split('[')[1].split(']')[0]}]"]`);
        if (hiddenInput) {
            hiddenInput.value = input.value;
        }
    });
    document.querySelector('input[name="PageNumber"]').value = 1;
    // Use fetch to submit the form
    triggerFormSubmission();
}

// Function to clear filters
function clearFilters() {
    document.querySelectorAll('input[name^="Filters"]').forEach(function (filterInput) {
        filterInput.value = '';
    });
    document.querySelectorAll('input[type="text"]').forEach(function (input) {
        input.value = '';
    });

    document.querySelector('input[name="PageNumber"]').value = 1;
    // Use fetch to submit the form
    triggerFormSubmission();
}
