function bodySetup() {
    let bodyEl = document.body;
    bodyEl.addEventListener('dragenter', (event) => event.preventDefault());
    bodyEl.addEventListener('dragover', (event) => event.preventDefault());
    bodyEl.addEventListener('drop', (event) => {
        event.preventDefault();
        dropUpload(event.dataTransfer.files);
    });
}

async function dropUpload(files) {
    if (!files.length) {
        alert('No files dropped.');
        return;
    }
    await uploadFile(files);
}

async function uploadFile(files = null) {
    const fileInput = document.getElementById('fileInput');
    const progressBar = document.getElementById('progressbar');
    files = files || fileInput.files;

    if (!files.length) {
        alert('Please select at least one file to upload.');
        return;
    }

    const formData = new FormData();
    let uploadedFiles = 0;

    for (const file of files) {
        formData.append('myFile', file);

        try {
            const xhr = new XMLHttpRequest();

            xhr.upload.onprogress = function (event) {
                if (event.lengthComputable) {
                    const percentComplete = (event.loaded / event.total) * 100;
                    progressBar.value = percentComplete;
                }
            };

            xhr.open('POST', '/upload', true);

            xhr.onload = function () {
                if (xhr.status === 200) {
                    uploadedFiles++;
                    console.log(`File uploaded: ${file.name}`);
                    if (uploadedFiles < files.length) {
                        progressBar.value = 0;
                    }
                    if (uploadedFiles === files.length) {
                        progressBar.value = 100;
                        alert('All files uploaded successfully!');
                    }
                } else {
                    alert(`Error uploading file: ${file.name}`);
                }
            };

            xhr.onerror = function () {
                alert(`Error uploading file: ${file.name}`);
            };

            xhr.send(formData);
            formData.delete('myFile');
        } catch (error) {
            alert(`Error uploading file: ${error.message}`);
        }
    }

    reloadFiles();
}

let fetchedFiles = [];

async function fetchFiles() {
    const filter = localStorage.getItem('fileFilter');
    const documentsFilter = ['doc', 'docx', 'ppt', 'pptx', 'pdf', 'txt', 'xls', 'xlsx', 'rar','zip','7zip'];
    const imagesFilter = ['jpeg', 'png', 'pneg', 'jpg', 'gif', 'webp', 'xls'];
    const appFilters = ['exe', 'apk'];
    const videoFilters = ['mov', 'mp4'];
    const musicFilters = ['mp3'];

    let extensions = [];
    if (filter === 'documents') extensions = documentsFilter;
    else if (filter === 'executables') extensions = appFilters;
    else if (filter === 'images') extensions = imagesFilter;
    else if (filter === 'video') extensions = videoFilters;
    else if (filter === 'music') extensions = musicFilters;
    else if (filter === 'applications') extensions = appFilters;

    const filterQuery = extensions.length > 0 ? extensions.join(',') : '';

    try {
        const response = await fetch(`/files/list?filter=${encodeURIComponent(filterQuery)}`);
        if (!response.ok) throw new Error(`Failed to fetch files: ${response.statusText}`);

        const files = await response.json();
        fetchedFiles = files;

        if (files && files.length > 0) {
            files.forEach(file => {
                document.querySelector('.folders-container').appendChild(generateFileMarkup(file));
            });
        } else {
            console.log('No files received from server');
        }
    } catch (error) {
        alert(`Error fetching files: ${error.message}`);
    }
}

function reloadFiles() {
    const foldersContainer = document.querySelector('.folders-container');
    foldersContainer.innerHTML = '';
    fetchFiles();
}

function generateFileMarkup(file) {
    if (!file || !file.name || !file.path) {
        console.warn('Invalid file item:', file);
        return '';
    }

    const imageExtensions = ['jpeg', 'jpg', 'png', 'gif', 'webp'];
    const videoExtensions = ['mov', 'mp4'];
    const musicExtensions = ['mp3'];
    const appExtensions = ['exe','apk'];

    const fileExtension = file.name.includes('.') ? file.name.split('.').pop().toLowerCase() : 'unknown';

    if (imageExtensions.includes(fileExtension)) {
        return createImageDisplay(file);
    } else if (videoExtensions.includes(fileExtension)) {
        return createVideoDisplay(file);
    } else if (musicExtensions.includes(fileExtension)) {
        return createMusicDisplay(file);
    } else if (appExtensions.includes(fileExtension)) {
        return createAppDisplay(file);
    } else {
        const fileIcons = {
            pdf: './resurse/pdf.png',
            ppt: './resurse/powerpoint.png',
            pptx: './resurse/powerpoint.png',
            doc: './resurse/docs.png',
            docx: './resurse/docs.png',
            xls: './resurse/excel.png',
            xlsx: './resurse/excel.png',
            exe: './resurse/exe.png',
            other: './resurse/paper.png',
        };
        const imageRoute = fileIcons[fileExtension] || fileIcons.other;
        return createFileDisplay(file, imageRoute);
    }
}

function handleAction(action) {
    if (action === "download") {
        downloadFiles();
    } else if (action === "delete") {
        deleteFiles();
    } else if (action === "selectAll") {
        selectAllFiles();
    } else if (action === "uselectAll") {
        usselectAllFiles();
    }
    document.querySelector('.itemOptions select').value = "";
}

let selectedFile = [];

function selectAllFiles() {
    selectedFile = [...fetchedFiles];

    const allItems = document.querySelectorAll('.fileDisplay, .imageDisplay, .videoDisplay, .appDisplay');
    allItems.forEach(item => {
        item.classList.add('selected');
    });

    console.log("All files have been selected:", selectedFile);
}

function usselectAllFiles() {
    selectedFile = [];
    const allItems = document.querySelectorAll('.fileDisplay, .imageDisplay, .videoDisplay, .appDisplay');
    allItems.forEach(item => item.classList.remove('selected'));
    console.log("All selections cleared");
}

function manageItem(container, item) {
    if (container.classList.contains('selected')) {
        container.classList.remove('selected');
        removeFromSelectedItems(item);
    } else {
        container.classList.add('selected');
        addToSelectedItems(item);
    }
}

function addToSelectedItems(item) {
    selectedFile.push(item);
}

function removeFromSelectedItems(item) {
    selectedFile = selectedFile.filter(selectedItem => selectedItem.path !== item.path);
}

async function deleteFiles() {
    if (selectedFile.length === 0) {
        alert("No files selected for deletion.");
        return;
    }

    let deleteSuccessCount = 0;
    let deleteFailCount = 0;

    for (const fileDoc of selectedFile) {
        const filePath = fileDoc.path;

        try {
            const response = await fetch('/files/delete', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ fileName: filePath })
            });

            if (response.ok) {
                deleteSuccessCount++;
            } else {
                const errorMessage = await response.text();
                console.error(`Error deleting file ${filePath}:`, errorMessage);
                deleteFailCount++;
            }
        } catch (error) {
            console.error(`Error deleting file ${filePath}:`, error);
            deleteFailCount++;
        }
    }

    if (deleteFailCount > 0) {
        alert(`Some files could not be deleted. ${deleteFailCount} failed.`);
    } else {
        alert("All selected files were deleted successfully.");
    }

    reloadFiles();
}

function downloadFiles() {
    if (selectedFile && selectedFile.length > 0) {
        const filePaths = selectedFile.map(fileDoc => fileDoc.path);
        const url = `/download/download-zip?paths=${encodeURIComponent(JSON.stringify(filePaths))}`;

        const link = document.createElement('a');
        link.href = url;
        link.download = 'files.zip';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        alert(`${selectedFile.length} files are being downloaded as a ZIP.`);
    } else {
        alert("No files selected for download.");
    }
}
