document.addEventListener('DOMContentLoaded', async function () {
    let ip = '';
    await window.electronAPI.readFile('ipConfig.json')
        .then(result => {
            const jsonData = JSON.parse(result.content);
            ip = jsonData.ip;
        })

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

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

    backButton.addEventListener('click', function () {
        fadeOut('main_menu.html');
        console.log('Back button clicked');
    });

    createButton.addEventListener('click', async function (e) {
        e.preventDefault();
        const departmentName = document.querySelector('input[name="text"]').value;
        if (!departmentName) {
            await window.electronAPI.showAlert('Department name is required.')
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
            return; // Exit if no name is provided
        }
        console.log(`Creating department: ${departmentName}`);

        const url = `http://${ip}/ceo/departments`;
        const headers = {
            'Content-Type': 'application/json',
            'x-api-key': 'uc_api',
            'ceo_password': password
        };
        console.log(headers);
        console.log(password);
        const body = JSON.stringify({ name: departmentName });

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: headers,
                body: body
            });

            if (response.ok) {
                const data = await response.json();
                await window.electronAPI.showAlert(data.message);
                document.querySelector('input[name="text"]').value = '';
                fadeOut('manage_departments.html');
            } else {
                console.log("eroare");
                const errorData = await response.json();
                await window.electronAPI.showAlert(errorData.message)
                    .then(() => console.log('Alert window opened'))
                    .catch(error => console.error('Error showing alert:', error));
            }
        } catch (error) {
            console.log("error");
            await window.electronAPI.showAlert(error)
                .then(() => console.log('Alert window opened'))
                .catch(error => console.error('Error showing alert:', error));
        }
    });

    submitButton.addEventListener('click', function () {
        // Handle the "Submit" button functionality here
        console.log('Submit button clicked');
        saveOrder();
    });

    document.addEventListener('DOMContentLoaded', function () {
        const list = document.getElementById('security_level_form_content');
        let draggedItem = null;

        for (const item of list.querySelectorAll('li')) {
            item.setAttribute('draggable', true);

            item.addEventListener('dragstart', function (e) {
                draggedItem = this;
                setTimeout(() => this.classList.add('hide'), 0);
            });

            item.addEventListener('dragend', function (e) {
                setTimeout(() => this.classList.remove('hide'), 0);
            });

            item.addEventListener('dragover', function (e) {
                e.preventDefault();
            });

            item.addEventListener('dragenter', function (e) {
                e.preventDefault();
                this.classList.add('over');
            });

            item.addEventListener('dragleave', function (e) {
                this.classList.remove('over');
            });

            item.addEventListener('drop', function (e) {
                e.preventDefault();
                this.classList.remove('over');
                if (this !== draggedItem) {
                    const items = Array.from(list.querySelectorAll('li'));
                    const draggedIndex = items.indexOf(draggedItem);
                    const droppedIndex = items.indexOf(this);

                    if (draggedIndex < droppedIndex) {
                        this.after(draggedItem);
                    } else {
                        this.before(draggedItem);
                    }
                }
            });
        }
    });

    function saveOrder() {
        const listItems = document.querySelectorAll('#security_level_form_content li');
        const order = Array.from(listItems).map(item => item.textContent.trim());
    }

    async function loadOrder() {
        const url = `http://${ip}/users/departments`; // Replace {serverip} with the actual IP address of the server

        try {
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': 'uc_api'
                }
            });

            if (response.ok) {
                let departments = await response.json();
                const list = document.getElementById('security_level_form_content');
                list.innerHTML = ''; // Clear existing items
                departments = departments.data;

                // Check if there's a stored order in localStorage and reorder the departments array accordingly
                const storedOrder = JSON.parse(localStorage.getItem('listOrder'));
                if (storedOrder) {
                    storedOrder.forEach(itemKey => {
                        if (departments[itemKey]) {
                            appendDepartmentToList(departments[itemKey], list);
                        }
                    });
                } else {
                    Object.keys(departments).forEach(key => {
                        appendDepartmentToList(departments[key], list);});
                }
            } else {
                console.error('Failed to fetch departments:', response.status);
            }
        } catch (error) {
            console.error('Error making the request:', error);
        }
    }

    function appendDepartmentToList(department, list) {
        const li = document.createElement('li');
        li.textContent = department.name;
        li.id = `department-${department.key}`; // Use a unique ID if possible, here it's prefixed with 'department-'
        li.setAttribute('draggable', true);
        list.appendChild(li);
    }

    await loadOrder();
});
