{% extends 'admin/base.html.twig' %}

{% block title %}Medya Kutuphanesi{% endblock %}
{% block page_title %}Medya Kutuphanesi{% endblock %}

{% block body %}
<div x-data="mediaManager()" x-init="init()">

    {# Action Bar #}
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6 gap-4">
        <div class="flex items-center gap-3">
            <button @click="$refs.fileInput.click()" type="button" class="btn-primary">
                <i class="fas fa-cloud-upload-alt mr-2"></i> Dosya Yukle
            </button>
            <input type="file" x-ref="fileInput" @change="handleFiles($event.target.files)" multiple class="hidden" accept="image/*,video/*,application/pdf,.doc,.docx,.xls,.xlsx,.zip,.rar">
        </div>

        <div class="flex items-center gap-3">
            {# Folder filter #}
            <form method="get" class="flex items-center gap-2">
                <select name="folder" onchange="this.form.submit()" class="form-input">
                    <option value="">Tum Klasorler</option>
                    {% for folder in folders %}
                        <option value="{{ folder }}" {{ currentFolder == folder ? 'selected' : '' }}>{{ folder|capitalize }}</option>
                    {% endfor %}
                </select>

                {# Search #}
                <input type="text" name="q" value="{{ searchQuery }}" placeholder="Medya ara..."
                       class="form-input w-48">
                <button type="submit" class="btn-outline">
                    <i class="fas fa-search"></i>
                </button>
            </form>
        </div>
    </div>

    {# Drag & Drop Upload Zone #}
    <div
        @dragover.prevent="dragOver = true"
        @dragleave.prevent="dragOver = false"
        @drop.prevent="handleDrop($event)"
        :class="dragOver ? 'border-primary-500 bg-primary-50' : 'border-gray-300 bg-white'"
        class="relative border-2 border-dashed rounded-lg p-6 mb-6 text-center transition-colors duration-200"
        x-show="uploading || dragOver || mediaCount === 0"
        x-transition
    >
        <div x-show="!uploading">
            <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
            <p class="text-gray-600 font-medium">Dosyalari buraya surukleyin veya</p>
            <button @click="$refs.fileInput.click()" type="button" class="text-primary-600 hover:text-primary-500 font-semibold mt-1">
                bilgisayarinizdan secin
            </button>
            <p class="text-gray-400 text-sm mt-2">Maksimum dosya boyutu: 10MB</p>
        </div>

        {# Upload Progress #}
        <div x-show="uploading" x-cloak>
            <div class="flex items-center justify-center gap-3 mb-3">
                <svg class="animate-spin h-6 w-6 text-primary-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                </svg>
                <span class="text-gray-700 font-medium">Yukleniyor...</span>
            </div>
            <div class="w-full max-w-md mx-auto bg-gray-200 rounded-full h-2">
                <div class="bg-primary-600 h-2 rounded-full transition-all duration-300" :style="'width: ' + uploadProgress + '%'"></div>
            </div>
            <p class="text-sm text-gray-500 mt-2" x-text="uploadedCount + ' / ' + totalFiles + ' dosya yuklendi'"></p>
        </div>
    </div>

    {# Upload Errors #}
    <template x-if="uploadErrors.length > 0">
        <div class="mb-6 rounded-md bg-red-50 p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-times-circle text-red-400"></i>
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-medium text-red-800">Yukleme hatalari</h3>
                    <ul class="mt-2 text-sm text-red-700 list-disc list-inside">
                        <template x-for="err in uploadErrors" :key="err">
                            <li x-text="err"></li>
                        </template>
                    </ul>
                </div>
                <div class="ml-auto pl-3">
                    <button @click="uploadErrors = []" class="text-red-500 hover:text-red-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </template>

    {# Media Grid #}
    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4">
        {% for media in pagination %}
            <div class="card group relative overflow-hidden"
                 x-data="{ showActions: false }"
                 @mouseenter="showActions = true"
                 @mouseleave="showActions = false">
                {# Thumbnail #}
                <div class="aspect-square bg-gray-100 relative overflow-hidden">
                    {% if media.mimeType starts with 'image/' %}
                        <img src="{{ media.path }}" alt="{{ media.altText|default(media.originalName) }}" class="w-full h-full object-cover" loading="lazy">
                    {% elseif media.mimeType starts with 'video/' %}
                        <div class="w-full h-full flex items-center justify-center bg-gray-800">
                            <i class="fas fa-play-circle text-5xl text-white opacity-80"></i>
                        </div>
                    {% elseif media.mimeType == 'application/pdf' %}
                        <div class="w-full h-full flex items-center justify-center bg-red-50">
                            <i class="fas fa-file-pdf text-5xl text-red-500"></i>
                        </div>
                    {% elseif media.mimeType starts with 'application/vnd' or media.mimeType starts with 'application/msword' %}
                        <div class="w-full h-full flex items-center justify-center bg-blue-50">
                            <i class="fas fa-file-word text-5xl text-blue-500"></i>
                        </div>
                    {% else %}
                        <div class="w-full h-full flex items-center justify-center bg-gray-50">
                            <i class="fas fa-file text-5xl text-gray-400"></i>
                        </div>
                    {% endif %}

                    {# Hover Actions Overlay #}
                    <div x-show="showActions"
                         x-transition:enter="transition ease-out duration-200"
                         x-transition:enter-start="opacity-0"
                         x-transition:enter-end="opacity-100"
                         class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center gap-3">
                        <button @click.stop="openEditModal({
                                    id: {{ media.id }},
                                    altText: '{{ media.altText|default('')|e('js') }}',
                                    caption: '{{ media.caption|default('')|e('js') }}',
                                    folder: '{{ media.folder|e('js') }}',
                                    path: '{{ media.path|e('js') }}',
                                    originalName: '{{ media.originalName|e('js') }}',
                                    editToken: '{{ csrf_token('media_edit_' ~ media.id) }}'
                                })"
                                type="button"
                                class="p-2 bg-white rounded-full text-primary-600 hover:text-primary-800 hover:bg-gray-100 transition-colors"
                                title="Duzenle">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button @click.stop="copyPath('{{ media.path }}')"
                                type="button"
                                class="p-2 bg-white rounded-full text-gray-600 hover:text-gray-800 hover:bg-gray-100 transition-colors"
                                title="Yolu Kopyala">
                            <i class="fas fa-copy"></i>
                        </button>
                        <button @click.stop="confirmDelete({{ media.id }}, '{{ media.originalName|e('js') }}', '{{ csrf_token('delete_media_' ~ media.id) }}')"
                                type="button"
                                class="p-2 bg-white rounded-full text-red-600 hover:text-red-800 hover:bg-gray-100 transition-colors"
                                title="Sil">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>

                    {# Folder badge #}
                    <div class="absolute top-2 left-2">
                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-black bg-opacity-50 text-white">
                            <i class="fas fa-folder mr-1"></i> {{ media.folder }}
                        </span>
                    </div>
                </div>

                {# Info #}
                <div class="p-3">
                    <p class="text-sm font-medium text-gray-900 truncate" title="{{ media.originalName }}">
                        {{ media.originalName }}
                    </p>
                    <div class="flex items-center justify-between mt-1">
                        <span class="text-xs text-gray-500">
                            {% if media.size < 1024 %}
                                {{ media.size }} B
                            {% elseif media.size < 1048576 %}
                                {{ (media.size / 1024)|number_format(1, ',', '.') }} KB
                            {% else %}
                                {{ (media.size / 1048576)|number_format(2, ',', '.') }} MB
                            {% endif %}
                        </span>
                        <span class="text-xs text-gray-400">
                            {{ media.createdAt|date('d.m.Y') }}
                        </span>
                    </div>
                    {% if media.width and media.height %}
                        <p class="text-xs text-gray-400 mt-0.5">{{ media.width }}x{{ media.height }}px</p>
                    {% endif %}
                </div>
            </div>
        {% else %}
            <div class="col-span-full text-center py-16">
                <i class="fas fa-photo-video text-5xl text-gray-300 mb-4 block"></i>
                <p class="text-gray-500 text-lg">Henuz medya dosyasi eklenmemis.</p>
                <button @click="$refs.fileInput.click()" type="button" class="text-primary-600 hover:text-primary-500 font-semibold mt-2 inline-block">
                    Ilk dosyayi yukleyin
                </button>
            </div>
        {% endfor %}
    </div>

    {# Pagination #}
    {% if pagination.getTotalItemCount > 0 %}
        <div class="mt-6 flex items-center justify-between">
            <p class="text-sm text-gray-700">
                Toplam <span class="font-medium">{{ pagination.getTotalItemCount }}</span> medya dosyasi
            </p>
            <div class="knp-pagination">
                {{ knp_pagination_render(pagination) }}
            </div>
        </div>
    {% endif %}

    {# Edit Modal #}
    <div x-show="editModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto" aria-modal="true">
        <div class="flex items-center justify-center min-h-screen px-4">
            {# Backdrop #}
            <div x-show="editModal"
                 x-transition:enter="transition ease-out duration-200"
                 x-transition:enter-start="opacity-0"
                 x-transition:enter-end="opacity-100"
                 @click="editModal = false"
                 class="fixed inset-0 bg-gray-900 bg-opacity-50"></div>

            {# Modal content #}
            <div x-show="editModal"
                 x-transition:enter="transition ease-out duration-200"
                 x-transition:enter-start="opacity-0 scale-95"
                 x-transition:enter-end="opacity-100 scale-100"
                 class="relative bg-white rounded-lg shadow-xl max-w-2xl w-full z-10">
                <div class="flex items-center justify-between p-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">Medya Detaylari</h3>
                    <button @click="editModal = false" type="button" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>

                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {# Preview #}
                        <div>
                            <div class="aspect-square bg-gray-100 rounded-lg overflow-hidden">
                                <img :src="editData.path" :alt="editData.altText" class="w-full h-full object-contain">
                            </div>
                            <p class="text-sm text-gray-500 mt-2 truncate" x-text="editData.originalName"></p>
                        </div>

                        {# Form #}
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Alt Metin (SEO)</label>
                                <input type="text" x-model="editData.altText" class="form-input w-full" placeholder="Gorseli tanimlayan metin...">
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Aciklama</label>
                                <textarea x-model="editData.caption" rows="3" class="form-input w-full" placeholder="Medya aciklamasi..."></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Klasor</label>
                                <input type="text" x-model="editData.folder" class="form-input w-full" placeholder="Klasor adi...">
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Dosya Yolu</label>
                                <div class="flex gap-2">
                                    <input type="text" :value="editData.path" readonly class="form-input w-full bg-gray-50 text-gray-500">
                                    <button @click="copyPath(editData.path)" type="button" class="btn-outline flex-shrink-0" title="Kopyala">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3 p-4 border-t border-gray-200">
                    <button @click="editModal = false" type="button" class="btn-outline">
                        Iptal
                    </button>
                    <button @click="saveEdit()" type="button" class="btn-primary" :disabled="saving">
                        <span x-show="!saving">
                            <i class="fas fa-save mr-1"></i> Kaydet
                        </span>
                        <span x-show="saving" x-cloak>
                            <svg class="animate-spin h-4 w-4 inline mr-1" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                            </svg>
                            Kaydediliyor...
                        </span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    {# Delete Confirmation Modal #}
    <div x-show="deleteModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto" aria-modal="true">
        <div class="flex items-center justify-center min-h-screen px-4">
            <div x-show="deleteModal" x-transition @click="deleteModal = false" class="fixed inset-0 bg-gray-900 bg-opacity-50"></div>
            <div x-show="deleteModal" x-transition class="relative bg-white rounded-lg shadow-xl max-w-md w-full z-10 p-6">
                <div class="flex items-start gap-4">
                    <div class="flex-shrink-0 w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                        <i class="fas fa-exclamation-triangle text-red-600"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">Medya Sil</h3>
                        <p class="text-sm text-gray-500 mt-1">
                            <strong x-text="deleteData.name"></strong> dosyasini silmek istediginize emin misiniz?
                            Bu islem geri alinamaz.
                        </p>
                    </div>
                </div>
                <div class="flex items-center justify-end gap-3 mt-6">
                    <button @click="deleteModal = false" type="button" class="btn-outline">Vazgec</button>
                    <button @click="executeDelete()" type="button" class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                        <i class="fas fa-trash-alt mr-1"></i> Sil
                    </button>
                </div>
            </div>
        </div>
    </div>

    {# Copy Success Toast #}
    <div x-show="copyToast"
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 translate-y-2"
         x-transition:enter-end="opacity-100 translate-y-0"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100 translate-y-0"
         x-transition:leave-end="opacity-0 translate-y-2"
         x-cloak
         class="fixed bottom-6 right-6 z-50 bg-gray-900 text-white px-4 py-2 rounded-lg shadow-lg text-sm">
        <i class="fas fa-check mr-1"></i> Yol panoya kopyalandi
    </div>
</div>

{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script>
        function mediaManager() {
            return {
                // Upload state
                dragOver: false,
                uploading: false,
                uploadProgress: 0,
                uploadedCount: 0,
                totalFiles: 0,
                uploadErrors: [],
                mediaCount: {{ pagination|length }},

                // Edit modal state
                editModal: false,
                saving: false,
                editData: {
                    id: null,
                    altText: '',
                    caption: '',
                    folder: '',
                    path: '',
                    originalName: '',
                    editToken: ''
                },

                // Delete modal state
                deleteModal: false,
                deleteData: {
                    id: null,
                    name: '',
                    token: ''
                },

                // Toast
                copyToast: false,

                // CSRF token for upload
                csrfUploadToken: '{{ csrf_token("media_upload") }}',

                init() {},

                handleDrop(event) {
                    this.dragOver = false;
                    const files = event.dataTransfer.files;
                    if (files.length > 0) {
                        this.handleFiles(files);
                    }
                },

                async handleFiles(fileList) {
                    if (!fileList || fileList.length === 0) return;

                    this.uploading = true;
                    this.uploadErrors = [];
                    this.uploadedCount = 0;
                    this.totalFiles = fileList.length;
                    this.uploadProgress = 0;

                    for (let i = 0; i < fileList.length; i++) {
                        const file = fileList[i];

                        // Check file size (10MB max)
                        if (file.size > 10 * 1024 * 1024) {
                            this.uploadErrors.push(file.name + ': Dosya boyutu 10MB limitini asiyor.');
                            this.uploadedCount++;
                            this.uploadProgress = Math.round((this.uploadedCount / this.totalFiles) * 100);
                            continue;
                        }

                        const formData = new FormData();
                        formData.append('file', file);
                        formData.append('_token', this.csrfUploadToken);
                        formData.append('folder', '{{ currentFolder|default("genel") }}');

                        try {
                            const response = await fetch('{{ path("admin_media_upload") }}', {
                                method: 'POST',
                                body: formData,
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest'
                                }
                            });

                            if (!response.ok) {
                                // Try to get error from JSON, fallback to status text
                                try {
                                    const errResult = await response.json();
                                    this.uploadErrors.push(file.name + ': ' + (errResult.error || 'Sunucu hatası (' + response.status + ')'));
                                } catch(e) {
                                    this.uploadErrors.push(file.name + ': Sunucu hatası (' + response.status + ')');
                                }
                            } else {
                                const result = await response.json();
                                if (!result.success) {
                                    this.uploadErrors.push(file.name + ': ' + (result.error || 'Bilinmeyen hata'));
                                }
                            }
                        } catch (error) {
                            this.uploadErrors.push(file.name + ': Ağ hatası - ' + error.message);
                        }

                        this.uploadedCount++;
                        this.uploadProgress = Math.round((this.uploadedCount / this.totalFiles) * 100);
                    }

                    this.uploading = false;

                    // Reset file input
                    if (this.$refs.fileInput) {
                        this.$refs.fileInput.value = '';
                    }

                    // Reload page to show new files
                    if (this.uploadErrors.length < this.totalFiles) {
                        setTimeout(() => {
                            window.location.reload();
                        }, 500);
                    }
                },

                openEditModal(data) {
                    this.editData = {
                        id: data.id,
                        altText: data.altText,
                        caption: data.caption,
                        folder: data.folder,
                        path: data.path,
                        originalName: data.originalName,
                        editToken: data.editToken
                    };
                    this.editModal = true;
                },

                async saveEdit() {
                    this.saving = true;

                    const formData = new FormData();
                    formData.append('_token', this.editData.editToken);
                    formData.append('altText', this.editData.altText || '');
                    formData.append('caption', this.editData.caption || '');
                    formData.append('folder', this.editData.folder || 'genel');

                    try {
                        const response = await fetch('{{ path("admin_media") }}/' + this.editData.id + '/edit', {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        });

                        const result = await response.json();

                        if (result.success) {
                            this.editModal = false;
                            window.location.reload();
                        } else {
                            alert(result.error || 'Bir hata olustu.');
                        }
                    } catch (error) {
                        alert('Ag hatasi. Lutfen tekrar deneyin.');
                    }

                    this.saving = false;
                },

                copyPath(path) {
                    navigator.clipboard.writeText(path).then(() => {
                        this.copyToast = true;
                        setTimeout(() => { this.copyToast = false; }, 2000);
                    });
                },

                confirmDelete(id, name, token) {
                    this.deleteData = { id: id, name: name, token: token };
                    this.deleteModal = true;
                },

                async executeDelete() {
                    const formData = new FormData();
                    formData.append('_token', this.deleteData.token);

                    try {
                        const response = await fetch('{{ path("admin_media") }}/' + this.deleteData.id + '/delete', {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        });

                        const result = await response.json();

                        if (result.success) {
                            this.deleteModal = false;
                            window.location.reload();
                        } else {
                            alert(result.error || 'Silme islemi basarisiz oldu.');
                        }
                    } catch (error) {
                        alert('Ag hatasi. Lutfen tekrar deneyin.');
                    }
                }
            };
        }
    </script>
{% endblock %}
