<template>
    <div class="upload-files">
        <h2>Dateien hochladen</h2>
        <div>
            <label for="file-upload">Datei auswählen:</label>
            <input id="file-upload" type="file" @change="handleFileUpload" />
        </div>
        <div>
            <label for="file-title">Titel eingeben:</label>
            <input id="file-title" type="text" v-model="fileTitle" />
        </div>
        <button @click="uploadFiles">Hochladen</button>
        <ul class="file-list">
            <li v-for="file in uploadedFiles" :key="file.id">
                <div class="file-info">
                    <span class="file-title" @click="downloadFile(file)">{{ file.title }}</span>
                    <span class="file-name" @click="downloadFile(file)">{{ file.originalName }}</span>
                    <span class="file-date">{{ formatDate(file.createdAt) }}</span>
                </div>
            </li>
        </ul>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from '../../axios';

export default {
    name: 'UploadFilesComponent',
    setup() {
        const fileToUpload = ref(null);
        const fileTitle = ref('');
        const uploadedFiles = ref([]);

        const handleFileUpload = (event) => {
            fileToUpload.value = event.target.files[0];
        };

        const uploadFiles = async () => {
            if (!fileToUpload.value || !fileTitle.value) {
                alert('Bitte wählen Sie eine Datei aus und geben Sie einen Titel ein.');
                return;
            }

            const formData = new FormData();
            formData.append('file', fileToUpload.value);
            formData.append('title', fileTitle.value);

            try {
                const response = await axios.post('/files', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });

                const uploadedData = response.data;
                uploadedFiles.value.push({
                    id: uploadedData.id,
                    title: uploadedData.title,
                    originalName: uploadedData.originalName,
                    createdAt: uploadedData.createdAt,
                    hash: uploadedData.hash,
                });

                fileToUpload.value = null;
                fileTitle.value = '';
            } catch (error) {
                console.error('Fehler beim Hochladen der Datei:', error);
            }
        };

        const downloadFile = async (file) => {
            const fileExtension = file.originalName.substring(file.originalName.lastIndexOf('.'));
            const response = await axios.get(`/files/download/${file.hash}`, {
                responseType: 'blob'
            });
            const blob = new Blob([response.data], { type: response.data.type });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = `${file.title}${fileExtension}`;
            link.click();
            window.URL.revokeObjectURL(link.href);
        };

        const formatDate = (dateString) => {
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            return new Date(dateString).toLocaleDateString(undefined, options);
        };

        const fetchUploadedFiles = async () => {
            try {
                const response = await axios.get('/files');
                uploadedFiles.value = response.data;
            } catch (error) {
                console.error('Fehler beim Abrufen der Dateien:', error);
            }
        };

        onMounted(fetchUploadedFiles);

        return {
            fileToUpload,
            fileTitle,
            uploadedFiles,
            handleFileUpload,
            uploadFiles,
            downloadFile,
            formatDate,
        };
    },
};
</script>

<style scoped>
.upload-files {
    width: 100%;
    margin: auto;
}

.upload-files div {
    margin-bottom: 10px;
}

.file-list {
    list-style-type: none;
    padding: 0;
    margin-top: 20px;
}

.file-list li {
    border-bottom: 1px solid #ddd;
    padding: 10px 0;
}

.file-info {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
}

.file-title {
    font-weight: bold;
}

.file-name {
    color: #555;
}

.file-date {
    color: #888;
}
</style>
