document.addEventListener('DOMContentLoaded', async function () {
    const backupButton = document.getElementById('backup');
    const changeDepartmentButton = document.getElementById('change_department');
    const changeInfoButton = document.getElementById('change_info');
    const shareFileButton = document.getElementById('share_file');
    const decryptButton = document.getElementById('decrypt');
    const logoutButton = document.getElementById('logout');

    const overlay = document.getElementById('overlay');
    const ceoBackButton = document.getElementById('back_button');
    const ceoSubmitButton = document.getElementById('submit_button');

    let triggerSource = '';

    function handleOverlayOpen(buttonId) {
        overlay.style.display = 'block';
        triggerSource = buttonId; // Remember the button that triggered the overlay
        console.log(`${buttonId} button clicked!`);
    }

    changeDepartmentButton.addEventListener('click', function () {
        handleOverlayOpen('change_department');
    });

    decryptButton.addEventListener('click', function () {
        handleOverlayOpen('decrypt');
    });

    // Hide the form when the "Back" button is clicked
    ceoBackButton.addEventListener('click', function() {
        overlay.style.display = 'none';
    });

    // Validate and process the form when submitted
    ceoSubmitButton.addEventListener('click', async function(event) {
        event.preventDefault();
        const password = document.getElementById('ceo_password').value;

        if (password === '') {
            await window.electronAPI.showAlert('Please enter password')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        let fetchResult;
        let fetchJson = undefined;

        fetchResult = await fetch('http://localhost:5000/admin/reset_key', {
            method: 'GET',
            headers: {
                'x-api-key': 'uc_api'
            }
        })

        if(!fetchResult.ok){
            await window.electronAPI.showAlert('Internal server error. Please try again later!')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        fetchJson = await fetchResult.json();
        const adminKey = fetchJson['data'];

        fetchResult = await fetch('http://localhost:5000/admin/validate_admin_password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': 'uc_api',
                'admin-key': adminKey
            },
            body: JSON.stringify({
                password: password
            })
        })

        if(!fetchResult.ok){
            await window.electronAPI.showAlert('The password is incorrect')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return;
        }

        if (triggerSource === 'change_department') {
            window.electronAPI.changeContent('change_department.html')
                .then(() => console.log('Navigated to dashboard'))
                .catch(error => console.error('Error navigating:', error));
        } else if (triggerSource === 'decrypt') {
            await decryptFiles()
        }

        overlay.style.display = 'none';
        triggerSource = '';
    });

    checkDirBackupFileExists()
        .then(() => console.log('verificare facuta'));
    await insertUsername();

    backupButton.addEventListener('click', function () {
        console.log('Set backup directory button clicked!');

        window.electronAPI.openBackupDirDialog()
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));
    });

    changeInfoButton.addEventListener('click', function () {
        console.log('Change your info button clicked!');

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

    shareFileButton.addEventListener('click', function () {
        console.log('Share a file button clicked!');

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



    logoutButton.addEventListener('click', async function () {
        console.log('Logout button clicked!');

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

    async function checkDirBackupFileExists() {
        try {
            // Make an IPC call to check file existence
            const fileExists = await window.electronAPI.checkFileExists('dirBackup.json');

            if (!fileExists) {
                const notificationsDiv = document.getElementById('notifications');
                const button = document.createElement('button');
                button.id = 'backup_alert';
                button.name = 'alert';
                button.textContent = 'Set your backup directory!';
                button.addEventListener('click', handleButtonClick);
                notificationsDiv.appendChild(button);
            }
        } catch (error) {
            console.error('Error checking file existence:', error);
        }
    }


    async function handleButtonClick() {
        console.log('Button clicked!');

        await window.electronAPI.openBackupDirDialog()
            .then(() => console.log('Back-up directory set'))
            .catch(async error => await window.electronAPI.showAlert(error.message)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error)));

        const button = document.getElementById('backup_alert');
        button.remove();
    }

    async function insertUsername() {
        try {
            const userData = await window.electronAPI.readFile('loginData.json');
            const userJson = JSON.parse(userData.content);
            const username = userJson.name;

            const usernameField = document.getElementById('username_field');
            if (usernameField) {
                usernameField.textContent = username + '!';
            }
        } catch (error) {
            console.error('Error loading username:', error);
            const usernameField = document.getElementById('username_field');
            usernameField.textContent = 'User!';
        }
    }

    async function decryptFiles(){

    }
});
