@extends('layouts.app')

@section('title', $gallery->title)

@section('content')
<x-app-layout>
    <x-module-hero
        title="{{ $gallery->title }}"
        description="Gallery details and image management"
        icon="fa-image">

        <x-slot name="backButton">
            <a href="{{ route('media.galleries.index') }}"
               class="inline-flex items-center gap-2 text-[#475569] hover:text-[#1e293b] text-sm transition">
                <i class="fas fa-arrow-left text-xs"></i> Back to Galleries
            </a>
        </x-slot>

        <x-slot name="actions">
            @can('edit galleries')
            <a href="{{ route('media.galleries.edit', $gallery) }}"
               class="inline-flex items-center gap-2 px-4 py-2 bg-amber-600 text-white text-sm font-semibold rounded-lg hover:bg-amber-700 transition">
                <i class="fas fa-edit"></i> Edit Gallery
            </a>
            @endcan
            @can('delete galleries')
            <form action="{{ route('media.galleries.destroy', $gallery) }}" method="POST" class="inline"
                  onsubmit="return confirm('Delete this gallery and all its images?');">
                @csrf @method('DELETE')
                <button type="submit"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-sm font-semibold rounded-lg hover:bg-red-700 transition">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </form>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        {{-- Flash Messages --}}
        @if(session('success'))
        <div class="mb-6 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-check-circle"></i>
            <span>{{ session('success') }}</span>
        </div>
        @endif

        @if(session('error'))
        <div class="mb-6 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-times-circle"></i>
            <span>{{ session('error') }}</span>
        </div>
        @endif

        {{-- Gallery Info Cards --}}
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
            {{-- Gallery Type --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 mb-1">Gallery Type</p>
                <div class="flex items-center gap-2">
                    <i class="fas {{ $gallery->type->icon }} text-lg" style="color: {{ $gallery->type->color }}"></i>
                    <p class="font-semibold text-gray-900">{{ $gallery->type->name }}</p>
                </div>
            </div>

            {{-- Organization --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 mb-1">Organization</p>
                <p class="font-semibold text-gray-900">{{ $gallery->organization->name }}</p>
            </div>

            {{-- Image Count --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 mb-1">Total Images</p>
                <p class="font-semibold text-gray-900 text-2xl">{{ $gallery->images()->count() }}</p>
            </div>

            {{-- Status --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <p class="text-xs text-gray-500 mb-1">Status</p>
                <span class="inline-block px-2 py-1 text-xs font-semibold rounded-full
                    {{ $gallery->is_published ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800' }}">
                    {{ $gallery->is_published ? 'Published' : 'Draft' }}
                </span>
            </div>
        </div>

        {{-- Description --}}
        @if($gallery->description)
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
            <h3 class="text-sm font-medium text-gray-700 mb-2">Description</h3>
            <p class="text-gray-600 leading-relaxed">{{ $gallery->description }}</p>
        </div>
        @endif

        {{-- Image Upload Section --}}
        @can('upload gallery images')
        <div class="bg-blue-50 rounded-lg shadow-sm border border-blue-200 p-6 mb-8">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-cloud-upload-alt text-blue-600"></i> Upload Images
            </h3>

            <form id="uploadForm" action="{{ route('media.images.upload', $gallery) }}" method="POST" enctype="multipart/form-data">
                @csrf

                {{-- File Input (Hidden) --}}
                <input type="file" id="fileInput" name="images[]" multiple accept="image/*" class="hidden">

                {{-- Upload Area --}}
                <div id="uploadArea" class="border-2 border-dashed border-blue-300 bg-white rounded-lg p-8 text-center cursor-pointer hover:bg-blue-50 transition mb-4">
                    <i class="fas fa-images text-4xl text-blue-400 mb-3"></i>
                    <p class="text-gray-700 font-medium mb-1">Drag images here or click to select</p>
                    <p class="text-xs text-gray-500">Max 5MB per image, up to 20 images at once</p>
                </div>

                {{-- Selected Files Preview --}}
                <div id="filesPreview" class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6"></div>

                {{-- Image Details Form --}}
                <div id="imageDetailsContainer"></div>

                {{-- Upload Button --}}
                <button type="submit" id="submitBtn" disabled
                    class="w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-medium flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fas fa-check"></i> Upload Images
                </button>
            </form>
        </div>
        @endcan

        {{-- Gallery Images Grid --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-6">
                <i class="fas fa-images text-blue-600"></i> Gallery Images
            </h3>

            @if($gallery->images()->count() > 0)
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    @foreach($gallery->images as $image)
                        <div class="relative group bg-gray-50 rounded-lg overflow-hidden border border-gray-200">
                            {{-- Image Thumbnail --}}
                            <a href="{{ $image->getImageUrl() }}" target="_blank" class="block h-48 overflow-hidden">
                                <img src="{{ asset('storage/' . $image->image_path) }}"
                                     alt="{{ $image->title }}"
                                     class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300">
                            </a>

                            {{-- Overlay on Hover --}}
                            <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-all duration-300 flex items-end opacity-0 group-hover:opacity-100">
                                <div class="w-full bg-black bg-opacity-75 p-3 text-white text-sm">
                                    <p class="font-medium truncate">{{ $image->title }}</p>
                                    <p class="text-xs text-gray-300">{{ $image->getFormattedFileSize() }}</p>
                                </div>
                            </div>

                            {{-- Image Actions --}}
                            <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
                                @can('edit gallery images')
                                <button type="button" class="bg-blue-600 text-white p-2 rounded hover:bg-blue-700 transition" 
                                        onclick="editImage({{ $image->id }}, '{{ $image->title }}', '{{ $image->description }}')">
                                    <i class="fas fa-edit text-sm"></i>
                                </button>
                                @endcan
                                @can('delete gallery images')
                                <form action="{{ route('media.images.destroy', $image) }}" method="POST" class="inline"
                                      onsubmit="return confirm('Delete this image?');">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="bg-red-600 text-white p-2 rounded hover:bg-red-700 transition">
                                        <i class="fas fa-trash text-sm"></i>
                                    </button>
                                </form>
                                @endcan
                            </div>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="text-center py-12">
                    <i class="fas fa-inbox text-5xl text-gray-300 mb-4"></i>
                    <p class="text-gray-600 mb-6">No images in this gallery yet.</p>
                    @can('upload gallery images')
                    <p class="text-sm text-gray-500">Upload your first image using the form above.</p>
                    @endcan
                </div>
            @endif
        </div>
    </div>

    {{-- Edit Image Modal --}}
    <div id="editImageModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-lg p-6 max-w-md w-full mx-4">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">Edit Image</h3>

            <form id="editImageForm" method="POST">
                @csrf @method('PUT')

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Title</label>
                    <input type="text" id="editTitle" name="title" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                </div>

                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea id="editDescription" name="description" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"></textarea>
                </div>

                <div class="flex gap-3">
                    <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-medium">
                        Save
                    </button>
                    <button type="button" onclick="closeEditModal()" class="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 transition font-medium">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</x-app-layout>

<script>
// Drag and drop file upload
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const filesPreview = document.getElementById('filesPreview');
const imageDetailsContainer = document.getElementById('imageDetailsContainer');
const submitBtn = document.getElementById('submitBtn');

uploadArea.addEventListener('click', () => fileInput.click());

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('bg-blue-50');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('bg-blue-50');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('bg-blue-50');
    fileInput.files = e.dataTransfer.files;
    handleFiles();
});

fileInput.addEventListener('change', handleFiles);

function handleFiles() {
    const files = fileInput.files;
    filesPreview.innerHTML = '';
    imageDetailsContainer.innerHTML = '';

    if (files.length === 0) {
        submitBtn.disabled = true;
        return;
    }

    submitBtn.disabled = false;

    Array.from(files).forEach((file, index) => {
        // Preview
        const reader = new FileReader();
        reader.onload = (e) => {
            const preview = document.createElement('div');
            preview.className = 'relative rounded-lg overflow-hidden border border-gray-300';
            preview.innerHTML = `
                <img src="${e.target.result}" alt="Preview" class="w-full h-32 object-cover">
                <div class="absolute inset-0 bg-black bg-opacity-25"></div>
            `;
            filesPreview.appendChild(preview);
        };
        reader.readAsDataURL(file);

        // Details form
        const details = document.createElement('div');
        details.className = 'mb-4 p-4 bg-white border border-gray-300 rounded-lg';
        details.innerHTML = `
            <p class="text-sm font-medium text-gray-700 mb-2">Image ${index + 1}: ${file.name}</p>
            <input type="text" name="titles[]" placeholder="Image title" required class="w-full px-3 py-2 border border-gray-300 rounded mb-2 text-sm">
            <textarea name="descriptions[]" placeholder="Image description (optional)" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded text-sm"></textarea>
        `;
        imageDetailsContainer.appendChild(details);
    });
}

// Edit image modal
function editImage(imageId, title, description) {
    document.getElementById('editImageForm').action = `/dashboard/media/images/${imageId}/update-metadata`;
    document.getElementById('editTitle').value = title;
    document.getElementById('editDescription').value = description;
    document.getElementById('editImageModal').classList.remove('hidden');
}

function closeEditModal() {
    document.getElementById('editImageModal').classList.add('hidden');
}
</script>
@endsection
