{# app/templates/store/media.html #}
{% extends "store/base.html" %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/modals.html' import modal_simple, confirm_modal %}

{% block title %}Media Library{% endblock %}

{% block alpine_data %}storeMedia(){% endblock %}

{% block content %}
<!-- Page Header -->
{% call page_header_flex(title='Media Library', subtitle='Upload and manage your images, videos, and documents') %}
    <div class="flex items-center gap-4">
        {{ refresh_button(loading_var='loading', onclick='loadMedia()', variant='secondary') }}
        <button
            @click="showUploadModal = true"
            class="flex items-center justify-between px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg active:bg-purple-600 hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple"
        >
            <span x-html="$icon('upload', 'w-4 h-4 mr-2')"></span>
            Upload Files
        </button>
    </div>
{% endcall %}

{{ loading_state('Loading media library...') }}

{{ error_state('Error loading media') }}

<!-- Stats Cards -->
<div x-show="!loading" class="grid gap-6 mb-8 md:grid-cols-4">
    <!-- Total Files -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
            <span x-html="$icon('folder', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Files</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total">0</p>
        </div>
    </div>

    <!-- Images -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
            <span x-html="$icon('photograph', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Images</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.images">0</p>
        </div>
    </div>

    <!-- Videos -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
            <span x-html="$icon('play', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Videos</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.videos">0</p>
        </div>
    </div>

    <!-- Documents -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
            <span x-html="$icon('document-text', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Documents</p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.documents">0</p>
        </div>
    </div>
</div>

<!-- Filters -->
<div x-show="!loading" class="bg-white rounded-lg shadow-md dark:bg-gray-800 p-4 mb-6">
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <!-- Search -->
        <div class="md:col-span-2">
            <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500 dark:text-gray-400">
                    <span x-html="$icon('search', 'w-5 h-5')"></span>
                </span>
                <input
                    type="text"
                    x-model="filters.search"
                    @input.debounce.300ms="loadMedia()"
                    placeholder="Search files..."
                    class="w-full pl-10 pr-4 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
                >
            </div>
        </div>

        <!-- Type Filter -->
        <div>
            <select
                x-model="filters.type"
                @change="loadMedia()"
                class="w-full px-4 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
            >
                <option value="">All Types</option>
                <option value="image">Images</option>
                <option value="video">Videos</option>
                <option value="document">Documents</option>
            </select>
        </div>

        <!-- Folder Filter -->
        <div>
            <select
                x-model="filters.folder"
                @change="loadMedia()"
                class="w-full px-4 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-purple-400 focus:outline-none focus:shadow-outline-purple"
            >
                <option value="">All Folders</option>
                <option value="general">General</option>
                <option value="products">Products</option>
            </select>
        </div>
    </div>
</div>

<!-- Media Grid -->
<div x-show="!loading && !error">
    <!-- Empty State -->
    <div x-show="media.length === 0" class="bg-white rounded-lg shadow-md dark:bg-gray-800 p-12 text-center">
        <div class="text-gray-400 mb-4">
            <span x-html="$icon('photograph', 'w-16 h-16 mx-auto')"></span>
        </div>
        <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200 mb-2">No Media Files Yet</h3>
        <p class="text-gray-600 dark:text-gray-400 mb-4">Upload your first file to get started</p>
        <button
            @click="showUploadModal = true"
            class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700"
        >
            <span x-html="$icon('upload', 'w-4 h-4 inline mr-2')"></span>
            Upload Files
        </button>
    </div>

    <!-- Media Grid -->
    <div x-show="media.length > 0" class="grid gap-6 md:grid-cols-4 lg:grid-cols-6">
        <template x-for="item in media" :key="item.id">
            <div
                class="bg-white rounded-lg shadow-md dark:bg-gray-800 overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
                @click="selectMedia(item)"
            >
                <!-- Thumbnail/Preview -->
                <div class="aspect-square bg-gray-100 dark:bg-gray-700 relative">
                    <!-- Image preview -->
                    <template x-if="item.media_type === 'image'">
                        <img
                            :src="item.thumbnail_url || item.file_url"
                            :alt="item.original_filename"
                            class="w-full h-full object-cover"
                            @error="$el.src = '/static/store/img/placeholder.svg'"
                        >
                    </template>

                    <!-- Video icon -->
                    <template x-if="item.media_type === 'video'">
                        <div class="w-full h-full flex items-center justify-center text-gray-400">
                            <span x-html="$icon('play', 'w-12 h-12')"></span>
                        </div>
                    </template>

                    <!-- Document icon -->
                    <template x-if="item.media_type === 'document'">
                        <div class="w-full h-full flex items-center justify-center text-gray-400">
                            <span x-html="$icon('document-text', 'w-12 h-12')"></span>
                        </div>
                    </template>

                    <!-- Type badge -->
                    <div class="absolute top-2 right-2">
                        <span
                            class="px-2 py-1 text-xs font-medium rounded"
                            :class="{
                                'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100': item.media_type === 'image',
                                'bg-purple-100 text-purple-800 dark:bg-purple-800 dark:text-purple-100': item.media_type === 'video',
                                'bg-orange-100 text-orange-800 dark:bg-orange-800 dark:text-orange-100': item.media_type === 'document'
                            }"
                            x-text="item.media_type"
                        ></span>
                    </div>
                </div>

                <!-- Info -->
                <div class="p-3">
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200 truncate" x-text="item.original_filename"></p>
                    <p class="text-xs text-gray-500 dark:text-gray-400" x-text="formatFileSize(item.file_size)"></p>
                </div>
            </div>
        </template>
    </div>

    <!-- Pagination -->
    <div x-show="pagination.pages > 1" class="mt-6">
        {{ pagination('pagination.pages > 1') }}
    </div>
</div>

<!-- Upload Modal -->
<div
    x-show="showUploadModal"
    x-cloak
    class="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black bg-opacity-50"
    @click.self="showUploadModal = false"
>
    <div class="relative w-full max-w-xl mx-4 bg-white rounded-lg shadow-lg dark:bg-gray-800" @click.stop>
        <!-- Modal Header -->
        <div class="flex items-center justify-between px-6 py-4 border-b dark:border-gray-700">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Upload Files</h3>
            <button @click="showUploadModal = false" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                <span x-html="$icon('x', 'w-5 h-5')"></span>
            </button>
        </div>

        <!-- Modal Body -->
        <div class="px-6 py-4">
            <!-- Folder Selection -->
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">Upload to Folder</label>
                <select
                    x-model="uploadFolder"
                    class="w-full px-4 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                >
                    <option value="general">General</option>
                    <option value="products">Products</option>
                </select>
            </div>

            <!-- Drop Zone -->
            <div
                class="border-2 border-dashed rounded-lg p-8 text-center transition-colors"
                :class="isDragging ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20' : 'border-gray-300 dark:border-gray-600'"
                @dragover.prevent="isDragging = true"
                @dragleave.prevent="isDragging = false"
                @drop.prevent="handleDrop($event)"
            >
                <input
                    type="file"
                    multiple
                    accept="image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt"
                    class="hidden"
                    x-ref="fileInput"
                    @change="handleFileSelect($event)"
                >

                <div class="text-gray-400 mb-4">
                    <span x-html="$icon('cloud-upload', 'w-12 h-12 mx-auto')"></span>
                </div>
                <p class="text-gray-600 dark:text-gray-400 mb-2">Drag and drop files here, or</p>
                <button
                    @click="$refs.fileInput.click()"
                    class="px-4 py-2 text-sm font-medium text-purple-600 border border-purple-600 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-900/20"
                >
                    Browse Files
                </button>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-4">
                    Supported: Images (10MB), Videos (100MB), Documents (20MB)
                </p>
            </div>

            <!-- Upload Progress -->
            <div x-show="uploadingFiles.length > 0" class="mt-4 space-y-2">
                <template x-for="file in uploadingFiles" :key="file.name">
                    <div class="flex items-center gap-3 p-2 bg-gray-50 dark:bg-gray-700 rounded">
                        <div class="flex-shrink-0">
                            <span x-html="$icon(file.status === 'success' ? 'check-circle' : file.status === 'error' ? 'x-circle' : 'spinner', 'w-5 h-5')"
                                  :class="{
                                      'text-green-500': file.status === 'success',
                                      'text-red-500': file.status === 'error',
                                      'text-gray-400 animate-spin': file.status === 'uploading'
                                  }"></span>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-sm text-gray-700 dark:text-gray-200 truncate" x-text="file.name"></p>
                            <p x-show="file.error" class="text-xs text-red-500" x-text="file.error"></p>
                        </div>
                        <div class="text-xs text-gray-500" x-text="file.status === 'uploading' ? 'Uploading...' : file.status"></div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Modal Footer -->
        <div class="flex justify-end gap-3 px-6 py-4 border-t dark:border-gray-700">
            <button
                @click="showUploadModal = false"
                class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600"
            >
                Close
            </button>
        </div>
    </div>
</div>

<!-- Media Detail Modal -->
<div
    x-show="showDetailModal"
    x-cloak
    class="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black bg-opacity-50"
    @click.self="showDetailModal = false"
>
    <div class="relative w-full max-w-2xl mx-4 bg-white rounded-lg shadow-lg dark:bg-gray-800" @click.stop>
        <!-- Modal Header -->
        <div class="flex items-center justify-between px-6 py-4 border-b dark:border-gray-700">
            <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Media Details</h3>
            <button @click="showDetailModal = false" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                <span x-html="$icon('x', 'w-5 h-5')"></span>
            </button>
        </div>

        <!-- Modal Body -->
        <div class="px-6 py-4" x-show="selectedMedia">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Preview -->
                <div class="bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden">
                    <template x-if="selectedMedia?.media_type === 'image'">
                        <img loading="lazy" :src="selectedMedia?.file_url" :alt="selectedMedia?.original_filename" class="w-full h-auto">
                    </template>
                    <template x-if="selectedMedia?.media_type !== 'image'">
                        <div class="aspect-square flex items-center justify-center text-gray-400">
                            <span x-html="$icon(selectedMedia?.media_type === 'video' ? 'play' : 'document-text', 'w-16 h-16')"></span>
                        </div>
                    </template>
                </div>

                <!-- Details -->
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Filename</label>
                        <input
                            type="text"
                            x-model="editingMedia.filename"
                            class="w-full px-3 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                        >
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Alt Text</label>
                        <input
                            type="text"
                            x-model="editingMedia.alt_text"
                            placeholder="Describe this image for accessibility"
                            class="w-full px-3 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                        >
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Description</label>
                        <textarea
                            x-model="editingMedia.description"
                            rows="2"
                            class="w-full px-3 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                        ></textarea>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Folder</label>
                        <select
                            x-model="editingMedia.folder"
                            class="w-full px-3 py-2 text-sm border rounded-lg dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                        >
                            <option value="general">General</option>
                            <option value="products">Products</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-2 gap-4 text-sm text-gray-600 dark:text-gray-400">
                        <div>
                            <span class="font-medium">Type:</span>
                            <span x-text="selectedMedia?.media_type"></span>
                        </div>
                        <div>
                            <span class="font-medium">Size:</span>
                            <span x-text="formatFileSize(selectedMedia?.file_size)"></span>
                        </div>
                        <div x-show="selectedMedia?.width">
                            <span class="font-medium">Dimensions:</span>
                            <span x-text="`${selectedMedia?.width}x${selectedMedia?.height}`"></span>
                        </div>
                    </div>

                    <!-- File URL -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">File URL</label>
                        <div class="flex gap-2">
                            <input
                                type="text"
                                :value="selectedMedia?.file_url"
                                readonly
                                class="flex-1 px-3 py-2 text-sm border rounded-lg bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300"
                            >
                            <button
                                @click="copyToClipboard(selectedMedia?.file_url)"
                                class="px-3 py-2 text-sm border rounded-lg hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700"
                                title="Copy URL"
                            >
                                <span x-html="$icon('clipboard-copy', 'w-4 h-4')"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal Footer -->
        <div class="flex justify-between px-6 py-4 border-t dark:border-gray-700">
            <button
                @click="showDeleteMediaConfirm = true"
                class="px-4 py-2 text-sm font-medium text-red-600 border border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20"
                :disabled="saving"
            >
                <span x-html="$icon('trash', 'w-4 h-4 inline mr-1')"></span>
                Delete
            </button>
            <div class="flex gap-3">
                <button
                    @click="showDetailModal = false"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600 dark:hover:bg-gray-600"
                >
                    Cancel
                </button>
                <button
                    @click="saveMediaDetails()"
                    class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700"
                    :disabled="saving"
                >
                    <span x-show="saving" class="inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></span>
                    Save Changes
                </button>
            </div>
        </div>
    </div>
</div>

{{ confirm_modal(
    'deleteMediaModal',
    'Delete File',
    'Are you sure you want to delete this file? This action cannot be undone.',
    'deleteMedia()',
    'showDeleteMediaConfirm',
    'Delete',
    'Cancel',
    'danger'
) }}
{% endblock %}

{% block extra_scripts %}
<script defer src="{{ url_for('cms_static', path='store/js/media.js') }}"></script>
{% endblock %}
