{{-- resources/views/admin/media/edit.blade.php --}}
@extends('admin.layouts.app')

@section('title', admin_trans('edit_file'))
@section('page-title', admin_trans('edit_file'))

@section('content')
<div class="max-w-4xl mx-auto" x-data="mediaEditor()">
    
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center gap-4">
            <x-button variant="outline" size="sm" icon="arrow-right" href="{{ route('admin.media.index') }}">
                {{ admin_trans('back_to_library') }}
            </x-button>
            <h1 class="text-2xl font-bold text-primary">{{ admin_trans('edit_file') }}</h1>
        </div>
        
        <div class="flex gap-2">
            <x-button variant="outline" icon="download" href="{{ route('admin.media.download', $media) }}">
                {{ admin_trans('download') }}
            </x-button>
            <x-button variant="danger" icon="trash-2" @click="deleteMedia()">
                {{ admin_trans('delete') }}
            </x-button>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        <!-- Media Preview -->
        <x-card :title="admin_trans('file_preview')" icon="eye">
            <div class="text-center">
                @if(str_starts_with($media->mime_type, 'image/'))
                    @php
                        // محاولة الحصول على الرابط بطرق مختلفة
                        $url = null;
                        $customProperties = $media->custom_properties ?? [];
                        
                        if (isset($customProperties['path'])) {
                            $url = asset('storage/' . $customProperties['path']);
                        } else {
                            // محاولة استخدام getUrl إذا كان متاح
                            try {
                                $url = $media->getUrl();
                            } catch (\Exception $e) {
                                // إذا فشل، جرب البحث في المجلد الافتراضي
                                $possiblePaths = [
                                    "media/{$media->id}/{$media->file_name}",
                                    "media/{$media->file_name}",
                                    $media->file_name
                                ];
                                
                                foreach ($possiblePaths as $path) {
                                    if (Storage::disk('public')->exists($path)) {
                                        $url = asset('storage/' . $path);
                                        break;
                                    }
                                }
                            }
                        }
                    @endphp
                    
                    @if($url)
                        <img src="{{ $url }}" 
                             alt="{{ $media->name }}" 
                             class="max-w-full max-h-96 rounded-lg border shadow-sm mx-auto">
                    @else
                        <div class="w-64 h-64 mx-auto bg-gray-100 rounded-lg flex items-center justify-center">
                            <div class="text-center">
                                <i data-lucide="image-off" class="w-16 h-16 text-gray-400 mx-auto mb-2"></i>
                                <p class="text-sm text-gray-500">{{ admin_trans('image_not_available') }}</p>
                                <p class="text-xs text-gray-400 mt-1">{{ $media->file_name }}</p>
                            </div>
                        </div>
                    @endif
                @elseif(str_starts_with($media->mime_type, 'video/'))
                    <div class="w-64 h-64 mx-auto bg-gradient-to-br from-purple-100 to-purple-200 rounded-lg flex items-center justify-center">
                        <div class="text-center">
                            <i data-lucide="video" class="w-16 h-16 text-purple-600 mx-auto mb-2"></i>
                            <p class="text-sm text-purple-700 font-medium">{{ admin_trans('video_file') }}</p>
                            <p class="text-xs text-purple-600 mt-1">{{ $media->file_name }}</p>
                        </div>
                    </div>
                @else
                    <div class="w-64 h-64 mx-auto bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg flex items-center justify-center">
                        <div class="text-center">
                            <i data-lucide="file-text" class="w-16 h-16 text-blue-600 mx-auto mb-2"></i>
                            <p class="text-sm text-blue-700 font-medium">{{ admin_trans('document') }}</p>
                            <p class="text-xs text-blue-600 mt-1">{{ $media->file_name }}</p>
                        </div>
                    </div>
                @endif
            </div>

            <!-- File Info -->
            <div class="mt-6 space-y-3 text-sm">
                <div class="flex justify-between">
                    <span class="font-medium text-tertiary">{{ admin_trans('filename') }}:</span>
                    <span class="text-primary">{{ $media->file_name }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-tertiary">{{ admin_trans('size') }}:</span>
                    <span class="text-primary">{{ number_format($media->size / 1024, 1) }} KB</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-tertiary">{{ admin_trans('element_type') }}:</span>
                    <span class="text-primary">{{ $media->mime_type }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-tertiary">{{ admin_trans('upload_date') }}:</span>
                    <span class="text-primary">{{ $media->created_at->format('d/m/Y H:i') }}</span>
                </div>
            </div>
        </x-card>

        <!-- Edit Form -->
        <x-card :title="admin_trans('edit_file_data')" icon="edit">
            <form action="{{ route('admin.media.update', $media) }}" method="POST" class="space-y-6">
                @csrf
                @method('PUT')

                <!-- File Name -->
                <div>
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('filename') }}</label>
                    <input type="text" name="name" value="{{ old('name', $media->name) }}"
                           class="input @error('name') border-red-500 @enderror" required>
                    @error('name')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Collection -->
                <div>
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('collection') }}</label>
                    <select name="collection_name" class="input @error('collection_name') border-red-500 @enderror">
                        <option value="default" {{ old('collection_name', $media->collection_name) === 'default' ? 'selected' : '' }}>{{ admin_trans('collection_default') }}</option>
                        <option value="logo" {{ old('collection_name', $media->collection_name) === 'logo' ? 'selected' : '' }}>{{ admin_trans('collection_logo') }}</option>
                        <option value="gallery" {{ old('collection_name', $media->collection_name) === 'gallery' ? 'selected' : '' }}>{{ admin_trans('collection_gallery') }}</option>
                        <option value="icon" {{ old('collection_name', $media->collection_name) === 'icon' ? 'selected' : '' }}>{{ admin_trans('collection_icon') }}</option>
                        <option value="banner" {{ old('collection_name', $media->collection_name) === 'banner' ? 'selected' : '' }}>{{ admin_trans('collection_banner') }}</option>
                    </select>
                    @error('collection_name')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Model Type -->
                <div>
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('element_type') }}</label>
                    <select name="model_type" x-model="selectedModelType" @change="loadModelItems()"
                            class="input @error('model_type') border-red-500 @enderror" required>
                        <option value="">{{ admin_trans('select_type') }}</option>
                        @foreach($availableModels as $class => $label)
                            <option value="{{ $class }}" {{ old('model_type', $media->model_type) === $class ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                        @endforeach
                    </select>
                    @error('model_type')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Model Item -->
                <div>
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('element') }}</label>
                    <select name="model_id" x-model="selectedModelId"
                            class="input @error('model_id') border-red-500 @enderror" required>
                        <option value="">{{ admin_trans('select_element') }}</option>
                        <template x-for="(name, id) in currentModelItems" :key="id">
                            <option :value="id" x-text="name" :selected="id == {{ old('model_id', $media->model_id) }}"></option>
                        </template>
                    </select>
                    @error('model_id')
                        <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Action Buttons -->
                <div class="flex gap-3 pt-4 border-t" style="border-color: var(--color-border);">
                    <x-button type="submit" variant="primary" icon="save">
                        {{ admin_trans('save_changes') }}
                    </x-button>
                    <x-button type="button" variant="outline" icon="x" href="{{ route('admin.media.index') }}">
                        {{ admin_trans('cancel') }}
                    </x-button>
                </div>
            </form>
        </x-card>
    </div>
</div>

@push('scripts')
<script>
function mediaEditor() {
    return {
        selectedModelType: '{{ old('model_type', $media->model_type) }}',
        selectedModelId: '{{ old('model_id', $media->model_id) }}',
        allModelItems: @json($modelItems),
        currentModelItems: {},

        init() {
            if (this.selectedModelType) {
                this.loadModelItems();
            }
        },

        loadModelItems() {
            if (this.selectedModelType && this.allModelItems[this.selectedModelType]) {
                this.currentModelItems = this.allModelItems[this.selectedModelType];
            } else {
                this.currentModelItems = {};
                this.selectedModelId = '';
            }
        },

        async deleteMedia() {
            if (!confirm('{{ admin_trans("confirm_delete_file") }}')) return;

            try {
                const response = await fetch('{{ route("admin.media.destroy", $media) }}', {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });

                const result = await response.json();
                if (result.success) {
                    toast.success('{{ admin_trans("file_deleted_successfully") }}');
                    setTimeout(() => {
                        window.location.href = '{{ route("admin.media.index") }}';
                    }, 1000);
                }
            } catch (error) {
                toast.error('{{ admin_trans("error_deleting_file") }}');
            }
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});
</script>
@endpush

@endsection