<script lang="ts">
    import { onMount } from 'svelte';
    import { api, type FileEntity } from '$lib/api';
    import { authStore } from '$lib/stores/auth.svelte.js';
    import FileUploader from '$lib/components/FileUploader.svelte';
    import { fade } from 'svelte/transition';

    let files = $state<FileEntity[]>([]);
    let loading = $state(true);
    let error = $state<string | null>(null);
    let showUploader = $state(false);

    async function loadFiles() {
        loading = true;
        const res = await api.getGeneralFiles();
        if (res.data) {
            files = res.data;
            error = null;
        } else {
            error = res.error || 'Failed to load files';
        }
        loading = false;
    }

    async function deleteFile(id: number) {
        if (!confirm('Are you sure you want to delete this file?')) return;
        
        const res = await api.deleteFile(id);
        if (res.data?.success) {
            files = files.filter(f => f.id !== id);
        } else {
            alert(res.error || 'Failed to delete file');
        }
    }

    function formatSize(bytes: number) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    function formatDate(dateStr: string) {
        return new Date(dateStr).toLocaleString();
    }

    onMount(() => {
        loadFiles();
    });
</script>

<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-8">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">File Repository</h1>
            <p class="text-gray-600 mt-1">General documents and resources</p>
        </div>
        
        {#if authStore.user?.role === 'Lehrer'}
            <button 
                class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-dark transition-colors flex items-center gap-2"
                onclick={() => showUploader = !showUploader}
            >
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                </svg>
                {showUploader ? 'Hide Uploader' : 'Upload File'}
            </button>
        {/if}
    </div>

    {#if showUploader && authStore.user?.role === 'Lehrer'}
        <div class="mb-8" transition:fade>
            <div class="bg-white p-6 rounded-lg shadow-md border border-gray-200">
                <h2 class="text-lg font-semibold mb-4">Upload New File</h2>
                <FileUploader onUploadSuccess={() => {
                    loadFiles();
                    showUploader = false;
                }} />
            </div>
        </div>
    {/if}

    {#if loading}
        <div class="flex justify-center py-12">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
        </div>
    {:else if error}
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
            <strong class="font-bold">Error!</strong>
            <span class="block sm:inline">{error}</span>
        </div>
    {:else if files.length === 0}
        <div class="text-center py-12 bg-gray-50 rounded-lg border border-gray-200">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-16 h-16 mx-auto text-gray-400 mb-4">
              <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
            </svg>
            <p class="text-lg text-gray-600">No files found</p>
        </div>
    {:else}
        <div class="bg-white shadow overflow-hidden rounded-lg border border-gray-200">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Size</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Uploaded By</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                        <th scope="col" class="relative px-6 py-3"><span class="sr-only">Actions</span></th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {#each files as file}
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 text-gray-400 mr-3">
                                      <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                                    </svg>
                                    <div class="text-sm font-medium text-gray-900">{file.filename}</div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500">{file.mimetype}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500">{formatSize(file.size)}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900">{file.uploadedBy.username}</div>
                                <div class="text-xs text-gray-500">{file.uploadedBy.role}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-500">{formatDate(file.createdAt)}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                <a 
                                    href={api.getDownloadUrl(file.id)} 
                                    target="_blank"
                                    class="text-primary hover:text-primary-dark mr-4"
                                >
                                    Download
                                </a>
                                {#if authStore.user?.role === 'Lehrer' || authStore.user?.id === file.uploadedById}
                                    <button 
                                        onclick={() => deleteFile(file.id)}
                                        class="text-red-600 hover:text-red-900"
                                    >
                                        Delete
                                    </button>
                                {/if}
                            </td>
                        </tr>
                    {/each}
                </tbody>
            </table>
        </div>
    {/if}
</div>
