document.addEventListener('DOMContentLoaded', async function () {
    try {
        const result = await window.electronAPI.readFile('loginData.json');
        const loginData = JSON.parse(result.content);

        // Set values for the inputs
        const emailInput = document.querySelector('input[name="email"]');
        const usernameInput = document.querySelector('input[name="username"]');
        const passwordInput = document.querySelector('input[name="password"]');

        emailInput.value = loginData.email;
        usernameInput.value = loginData.name;
        passwordInput.value = loginData.password;

    } catch (error) {
        console.error('Error reading login data:', error);
    }

    const backButton = document.querySelector('button[name="login"]');
    const submitButton = document.querySelector('button[name="submit"]');

    // Add event listeners for the back and submit buttons
    backButton.addEventListener('click', function () {
        console.log('Back button clicked!');

        window.electronAPI.changeContent('main_menu.html')
            .then(() => console.log('Navigated to dashboard'))
            .catch(error => console.error('Error navigating:', error));
    });

    submitButton.addEventListener('click', async function (e) {
        try {
            e.preventDefault();
            console.log('Submit button clicked!');

            const emailInput = document.querySelector('input[name="email"]');
            const usernameInput = document.querySelector('input[name="username"]');
            const passwordInput = document.querySelector('input[name="password"]');

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

            const {id, department} = loginData;
            const email = emailInput.value;
            const name = usernameInput.value;
            const password = passwordInput.value;

            const response = await fetch(`http://localhost:5000/users/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api'
                },
                body: JSON.stringify({
                    name: name,
                    email: email,
                    password: password
                })
            });

            switch (response.status) {
                case 400:
                    throw new Error('Email format invalid!')
                case 409:
                    throw new Error('Email already in system!')
                case 500:
                    throw new Error('Internal server error. Try again later!')
            }

            await window.electronAPI.writeFile('loginData.json', JSON.stringify({
                id: id,
                name: name,
                email: email,
                password: password,
                department: department
            }));

            window.electronAPI.changeContent('main_menu.html')
                .then(() => console.log('Navigated to dashboard'))
                .catch(error => console.error('Error navigating:', error));
        }catch(error) {
            await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
        }
    });
});
