{{-- resources/views/components/media-picker.blade.php --}}
@props([
    'name' => 'media',
    'label' => 'اختيار صورة',
    'collection' => 'default',
    'accept' => 'image/*',
    'multiple' => false,
    'selected' => null,
    'preview' => true,
    'required' => false,
])

@php
$id = $attributes->get('id') ?? $name ?? 'media-picker-' . uniqid();
$selectedItems = $selected ? (is_array($selected) ? $selected : [$selected]) : [];
@endphp

<div x-data="mediaPicker()" class="w-full">
    @if($label)
        <label class="block text-sm font-semibold mb-2 text-primary">
            {{ $label }}
            @if($required)
                <span class="text-red-500">*</span>
            @endif
        </label>
    @endif

    <!-- Selected Media Preview -->
    @if($preview && !empty($selectedItems))
        <div class="mb-4 grid grid-cols-2 md:grid-cols-4 gap-4">
            @foreach($selectedItems as $item)
                <div class="relative group">
                    @if(is_string($item))
                        <img src="{{ $item }}" alt="Selected" class="w-full h-24 object-cover rounded-lg border">
                    @else
                        <img src="{{ $item['url'] ?? '' }}" alt="{{ $item['name'] ?? 'Selected' }}" class="w-full h-24 object-cover rounded-lg border">
                    @endif
                    <button type="button" 
                        onclick="removeSelectedMedia(this)"
                        class="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                        <i data-lucide="x" class="w-3 h-3"></i>
                    </button>
                    <input type="hidden" name="{{ $name }}{{ $multiple ? '[]' : '' }}" value="{{ is_string($item) ? $item : ($item['id'] ?? '') }}">
                </div>
            @endforeach
        </div>
    @endif

    <!-- Upload/Select Buttons -->
    <div class="flex gap-3">
        <!-- Upload Button -->
        <div class="relative">
            <input type="file" 
                   accept="{{ $accept }}" 
                   {{ $multiple ? 'multiple' : '' }}
                   @change="handleFileUpload($event)" 
                   class="hidden" 
                   x-ref="fileInput">
            
            <x-button type="button" variant="outline" icon="upload" @click="$refs.fileInput.click()">
                {{ admin_trans('upload_new') }}
            </x-button>
        </div>

        <!-- Select from Library -->
        <x-button type="button" variant="outline" icon="image" @click="openMediaLibrary()">
            {{ admin_trans('choose_from_library') }}
        </x-button>
    </div>

    <!-- Media Library Modal -->
    <x-modal :name="'media-library-' . $id" maxWidth="4xl">
        <div class="p-6" x-data="mediaLibraryPicker()">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-bold text-primary">{{ admin_trans('media_library') }}</h3>
                <button @click="$dispatch('close-modal', 'media-library-{{ $id }}')" class="p-2 rounded-lg hover:bg-primary-light">
                    <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
                </button>
            </div>

            <!-- Search and Filters -->
            <div class="flex gap-4 mb-6">
                <div class="flex-1">
                    <x-search-input 
                        placeholder="{{ admin_trans('search_media') }}" 
                        @input="searchMedia($event.target.value)"
                    />
                </div>
                <select @change="filterByType($event.target.value)" class="input">
                    <option value="">{{ admin_trans('all_types') }}</option>
                    <option value="image">{{ admin_trans('images') }}</option>
                    <option value="video">{{ admin_trans('videos') }}</option>
                    <option value="document">{{ admin_trans('documents') }}</option>
                </select>
            </div>

            <!-- Loading State -->
            <div x-show="loading" class="text-center py-8">
                <x-loading text="{{ admin_trans('loading_media') }}..." />
            </div>

            <!-- Media Grid -->
            <div x-show="!loading" class="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-3 max-h-96 overflow-y-auto">
                <template x-for="item in mediaItems" :key="item.id">
                    <div class="relative cursor-pointer group" 
                         @click="selectMediaItem(item)"
                         :class="selectedInPicker.includes(item.id) ? 'ring-2 ring-primary' : ''">
                        
                        <!-- Image Preview -->
                        <div class="aspect-square rounded-lg overflow-hidden border bg-gray-100">
                            <img :src="item.thumb_url || item.url" 
                                 :alt="item.name" 
                                 class="w-full h-full object-cover">
                        </div>

                        <!-- Selection Indicator -->
                        <div x-show="selectedInPicker.includes(item.id)" 
                             class="absolute top-1 right-1 w-6 h-6 bg-primary text-white rounded-full flex items-center justify-center">
                            <i data-lucide="check" class="w-3 h-3"></i>
                        </div>

                        <!-- File Name -->
                        <p class="text-xs text-center mt-1 truncate" x-text="item.name" :title="item.name"></p>
                    </div>
                </template>
            </div>

            <!-- No Results -->
            <div x-show="!loading && mediaItems.length === 0" class="text-center py-8">
                <i data-lucide="image" class="w-12 h-12 mx-auto text-gray-400 mb-4"></i>
                <p class="text-gray-500">{{ admin_trans('no_media_found') }}</p>
            </div>

            <!-- Actions -->
            <div class="flex justify-between items-center mt-6 pt-4 border-t" style="border-color: var(--color-border);">
                <p class="text-sm text-tertiary" x-show="selectedInPicker.length > 0">
                    <span x-text="selectedInPicker.length"></span> {{ admin_trans('items_selected') }}
                </p>
                <div class="flex gap-3">
                    <x-button variant="outline" @click="$dispatch('close-modal', 'media-library-{{ $id }}')">
                        {{ admin_trans('cancel') }}
                    </x-button>
                    <x-button variant="primary" @click="confirmSelection()" :disabled="selectedInPicker.length === 0">
                        {{ admin_trans('select') }}
                    </x-button>
                </div>
            </div>
        </div>
    </x-modal>
</div>

<script>
function mediaPicker() {
    return {
        selectedMedia: @js($selectedItems),

        openMediaLibrary() {
            window.dispatchEvent(new CustomEvent('open-modal', { detail: 'media-library-{{ $id }}' }));
        },

        async handleFileUpload(event) {
            const files = Array.from(event.target.files);
            if (files.length === 0) return;

            const formData = new FormData();
            files.forEach(file => formData.append('files[]', file));
            formData.append('collection', '{{ $collection }}');
            formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);

            try {
                const response = await fetch('/admin/media/upload', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    toast.success(result.message);
                    
                    // Add uploaded files to selection
                    result.files.forEach(file => {
                        this.addMediaToSelection({
                            id: file.id,
                            name: file.name,
                            url: file.url
                        });
                    });
                }
            } catch (error) {
                toast.error('{{ admin_trans("error_uploading_file") }}');
            }

            // Clear input
            event.target.value = '';
        },

        addMediaToSelection(media) {
            const container = this.$el.querySelector('.grid');
            if (!container) return;

            // Create preview element
            const previewDiv = document.createElement('div');
            previewDiv.className = 'relative group';
            previewDiv.innerHTML = `
                <img src="${media.url}" alt="${media.name}" class="w-full h-24 object-cover rounded-lg border">
                <button type="button" onclick="removeSelectedMedia(this)" class="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                    <i data-lucide="x" class="w-3 h-3"></i>
                </button>
                <input type="hidden" name="{{ $name }}{{ $multiple ? '[]' : '' }}" value="${media.id}">
            `;

            {{ $multiple ? 'container.appendChild(previewDiv);' : 'container.innerHTML = ""; container.appendChild(previewDiv);' }}
            
            // Re-initialize lucide icons
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        }
    }
}

function mediaLibraryPicker() {
    return {
        loading: true,
        mediaItems: [],
        selectedInPicker: [],
        searchQuery: '',
        typeFilter: '',

        async init() {
            await this.loadMedia();
        },

        async loadMedia() {
            this.loading = true;
            try {
                const params = new URLSearchParams();
                if (this.searchQuery) params.append('search', this.searchQuery);
                if (this.typeFilter) params.append('file_type', this.typeFilter);
                params.append('per_page', '48');

                const response = await fetch(`/admin/media?${params}`);
                const data = await response.text();
                
                // Extract media data from response (simplified)
                // In a real implementation, you'd have a dedicated API endpoint
                this.mediaItems = this.extractMediaFromResponse(data);
            } catch (error) {
                console.error('Error loading media:', error);
            } finally {
                this.loading = false;
            }
        },

        extractMediaFromResponse(html) {
            // This is a simplified version - you'd want a proper API endpoint
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const mediaElements = doc.querySelectorAll('.media-item');
            
            return Array.from(mediaElements).map(el => ({
                id: parseInt(el.dataset.id),
                name: el.querySelector('h4')?.textContent?.trim() || 'Unknown',
                url: el.querySelector('img')?.src || '',
                thumb_url: el.querySelector('img')?.src || ''
            }));
        },

        selectMediaItem(item) {
            {{ $multiple ? '
            const index = this.selectedInPicker.indexOf(item.id);
            if (index > -1) {
                this.selectedInPicker.splice(index, 1);
            } else {
                this.selectedInPicker.push(item.id);
            }
            ' : '
            this.selectedInPicker = [item.id];
            ' }}
        },

        confirmSelection() {
            const selectedItems = this.mediaItems.filter(item => 
                this.selectedInPicker.includes(item.id)
            );

            // Add selected items to the main picker
            selectedItems.forEach(item => {
                // Trigger the parent component's method
                this.$dispatch('media-selected', item);
            });

            this.$dispatch('close-modal', 'media-library-{{ $id }}');
        },

        async searchMedia(query) {
            this.searchQuery = query;
            await this.loadMedia();
        },

        async filterByType(type) {
            this.typeFilter = type;
            await this.loadMedia();
        }
    }
}

// Global function to remove selected media
function removeSelectedMedia(button) {
    button.closest('.relative.group').remove();
}
</script>