document.addEventListener("DOMContentLoaded", function() {
    let pathToFile = '';

    function updateFileName() {
        const fileNameElement = document.getElementById('fileName');
        if (pathToFile.trim() === '') {
            fileNameElement.textContent = 'No file chosen';
        } else {
            fileNameElement.textContent = pathToFile.split('\\').pop().split('/').pop();
        }
    }

    // Call the function to update file name on DOMContentLoaded
    updateFileName();

    async function fetchUsersAndCreateCheckboxes() {
        const result = await window.electronAPI.readFile('loginData.json');
        const loginData = JSON.parse(result.content);

        const {id} = loginData;

        fetch('http://localhost:5000/users', {
            method: 'GET',
            headers: {
                'x-api-key': 'uc_api'
            }
        })
            .then(response => response.json())
            .then(data => {
                const usersDiv = document.querySelector('.choose_user_form_content');
                usersDiv.innerHTML = '';
                data['data'].forEach(user => {
                    if (user.id !== id) {
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.name = 'users';
                        checkbox.value = user.id;

                        const label = document.createElement('label');
                        label.innerHTML = `${user.name}`;
                        label.insertBefore(checkbox, label.firstChild); // Insert checkbox before the label's first child

                        usersDiv.appendChild(label);
                    }
                });
            })
            .catch(error => console.error('Error fetching users:', error));
    }

    document.getElementById('selectFile').addEventListener('click', async function () {
        console.log('Select file button clicked');

        try {
            pathToFile = await window.electronAPI.openFileDialog();
            updateFileName();
        } catch (error) {
            console.error('Error opening file dialog:', error);
        }
    });

    document.getElementById('backButton').addEventListener('click', async function () {
        console.log('Back button clicked');

        try {
            await window.electronAPI.changeContent('main_menu.html');
            console.log('Content changed successfully');
        } catch (error) {
            console.error('Error changing content:', error);
        }
    });

    document.getElementById('submitButton').addEventListener('click', async function (event) {
        event.preventDefault();
        console.log('Submit button clicked');

        if (pathToFile === '' || pathToFile.length === 0) {
            await window.electronAPI.showAlert('File not chosen!')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error changing content:', error));
            return
        }

        const form = document.getElementById('userDestForm');
        const checkboxes = form.querySelectorAll('input[name="users"]');
        const selectedUserIds = [];

        checkboxes.forEach(checkbox => {
            if (checkbox.checked) {
                selectedUserIds.push(checkbox.value);
            }
        });

        if(selectedUserIds === []){
            await window.electronAPI.showAlert('No user selected!')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error changing content:', error));
            return;
        }

        //TODO: logic to send files
    });

    fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
