@extends('layouts.self-paced-dashboard')

@section('title', 'Media — ' . $subtopic->title)
@section('page-title', 'Subtopic Media')
@section('page-subtitle', $course->title . ' › ' . $topic->title . ' › ' . $subtopic->title)

@section('hero-actions')
    <a href="{{ route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic]) }}"
       class="inline-flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-lg transition border border-white/30">
        <i class="fas fa-arrow-left"></i> Back to Subtopic
    </a>
@endsection

@section('content')
<div x-data="mediaIndex()">

    {{-- Breadcrumb --}}
    <nav class="flex items-center gap-2 text-xs text-gray-400 mb-5 flex-wrap">
        <a href="{{ route('self-paced.dashboard.index') }}" class="hover:text-indigo-600 transition">Dashboard</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.index') }}" class="hover:text-indigo-600 transition">Courses</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.show', $course) }}" class="hover:text-indigo-600 transition">{{ Str::limit($course->title, 25) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.topics.index', $course) }}" class="hover:text-indigo-600 transition">Topics</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.topics.show', [$course, $topic]) }}" class="hover:text-indigo-600 transition">{{ Str::limit($topic->title, 25) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <a href="{{ route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic]) }}" class="hover:text-indigo-600 transition">{{ Str::limit($subtopic->title, 25) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <span class="text-gray-600 font-medium">Media</span>
    </nav>

    {{-- Upload Form --}}
    @can('create self-paced courses')
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-5">
        <h2 class="text-sm font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <i class="fas fa-upload text-indigo-500"></i> Upload New Media
        </h2>

        <form action="{{ route('self-paced.dashboard.courses.topics.subtopics.media.store', [$course, $topic, $subtopic]) }}"
              method="POST"
              enctype="multipart/form-data">
            @csrf

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">

                {{-- Title --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-tag text-gray-400 mr-1"></i> Title
                        <span class="text-gray-400 font-normal">(optional)</span>
                    </label>
                    <input type="text"
                           name="title"
                           value="{{ old('title') }}"
                           placeholder="Leave blank to use filename"
                           class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition @error('title') border-red-400 @enderror">
                    @error('title')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Type --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-photo-video text-gray-400 mr-1"></i> Media Type <span class="text-red-500">*</span>
                    </label>
                    <select name="type"
                            class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white @error('type') border-red-400 @enderror">
                        <option value="">— Select type —</option>
                        <option value="video"        {{ old('type') === 'video'        ? 'selected' : '' }}>Video</option>
                        <option value="image"        {{ old('type') === 'image'        ? 'selected' : '' }}>Image</option>
                        <option value="pdf"          {{ old('type') === 'pdf'          ? 'selected' : '' }}>PDF</option>
                        <option value="presentation" {{ old('type') === 'presentation' ? 'selected' : '' }}>Presentation</option>
                        <option value="excel"        {{ old('type') === 'excel'        ? 'selected' : '' }}>Excel</option>
                    </select>
                    @error('type')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- File --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-upload text-gray-400 mr-1"></i> File <span class="text-red-500">*</span>
                    </label>
                    <input type="file"
                           name="media_file"
                           class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition @error('media_file') border-red-400 @enderror">
                    <p class="text-xs text-gray-400 mt-1">Max file size: 500 MB</p>
                    @error('media_file')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                {{-- Sort Order --}}
                <div>
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                        <i class="fas fa-sort text-gray-400 mr-1"></i> Sort Order
                    </label>
                    <input type="number"
                           name="sort_order"
                           value="{{ old('sort_order', $media->count()) }}"
                           min="0"
                           class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition @error('sort_order') border-red-400 @enderror">
                    @error('sort_order')
                        <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <div class="mt-4 flex justify-end">
                <button type="submit"
                        class="inline-flex items-center gap-2 px-5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-lg transition shadow-sm">
                    <i class="fas fa-upload"></i> Upload Media
                </button>
            </div>
        </form>
    </div>
    @endcan

    {{-- Media Table --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
            <h2 class="text-sm font-semibold text-gray-800 flex items-center gap-2">
                <i class="fas fa-photo-video text-purple-500"></i>
                Attached Media
                <span class="ml-1 px-2 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full font-medium">
                    {{ $media->count() }}
                </span>
            </h2>
            @if($media->count() > 1)
            <span class="text-xs text-gray-400">
                <i class="fas fa-info-circle mr-1"></i> Drag rows to reorder
            </span>
            @endif
        </div>

        @if($media->isEmpty())
        <div class="px-5 py-16 text-center">
            <i class="fas fa-photo-video text-5xl text-gray-200 mb-4 block"></i>
            <p class="text-gray-400 text-sm font-medium">No media files uploaded yet.</p>
            <p class="text-gray-300 text-xs mt-1">Use the form above to upload the first media file.</p>
        </div>
        @else
        <div class="overflow-x-auto">
            <table class="w-full text-sm" id="media-table">
                <thead>
                    <tr>
                        <th class="bg-indigo-50 text-indigo-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide w-10">#</th>
                        <th class="bg-purple-50 text-purple-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Title</th>
                        <th class="bg-blue-50 text-blue-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Type</th>
                        <th class="bg-green-50 text-green-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">File Name</th>
                        <th class="bg-amber-50 text-amber-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">File Size</th>
                        <th class="bg-teal-50 text-teal-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Sort Order</th>
                        <th class="bg-gray-50 text-gray-600 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Actions</th>
                    </tr>
                </thead>
                <tbody id="media-tbody" class="divide-y divide-gray-50">
                    @foreach($media as $i => $item)
                    @php
                        $typeColors = [
                            'video'        => 'bg-blue-100 text-blue-700',
                            'image'        => 'bg-green-100 text-green-700',
                            'pdf'          => 'bg-red-100 text-red-700',
                            'presentation' => 'bg-orange-100 text-orange-700',
                            'excel'        => 'bg-emerald-100 text-emerald-700',
                        ];
                        $typeIcons = [
                            'video'        => 'fa-video',
                            'image'        => 'fa-image',
                            'pdf'          => 'fa-file-pdf',
                            'presentation' => 'fa-file-powerpoint',
                            'excel'        => 'fa-file-excel',
                        ];
                    @endphp
                    <tr class="odd:bg-white even:bg-gray-50 hover:bg-indigo-50/30 transition-colors border-b border-gray-100 last:border-0"
                        data-id="{{ $item->id }}">
                        <td class="px-4 py-3 text-gray-400 text-xs font-medium cursor-grab">
                            <i class="fas fa-grip-vertical text-gray-300 mr-1"></i>{{ $i + 1 }}
                        </td>
                        <td class="px-4 py-3">
                            <p class="font-semibold text-gray-800 text-sm">{{ $item->title ?? '—' }}</p>
                        </td>
                        <td class="px-4 py-3">
                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium {{ $typeColors[$item->type] ?? 'bg-gray-100 text-gray-600' }}">
                                <i class="fas {{ $typeIcons[$item->type] ?? 'fa-file' }} text-xs"></i>
                                {{ ucfirst($item->type) }}
                            </span>
                        </td>
                        <td class="px-4 py-3 text-xs text-gray-600 max-w-[200px] truncate">
                            {{ $item->file_name }}
                        </td>
                        <td class="px-4 py-3 text-xs text-gray-600">
                            {{ $item->getFormattedFileSize() }}
                        </td>
                        <td class="px-4 py-3">
                            <span class="text-xs font-medium text-teal-700 bg-teal-50 px-2 py-0.5 rounded-full">
                                {{ $item->sort_order }}
                            </span>
                        </td>
                        <td class="px-4 py-3">
                            @can('delete self-paced courses')
                            <button type="button"
                                    onclick="confirmMediaDelete({{ $item->id }}, '{{ addslashes($item->title ?? $item->file_name) }}')"
                                    class="w-7 h-7 flex items-center justify-center rounded-lg bg-red-50 hover:bg-red-100 text-red-600 transition">
                                <i class="fas fa-trash text-xs"></i>
                            </button>
                            <form id="delete-media-form-{{ $item->id }}"
                                  action="{{ route('self-paced.dashboard.courses.topics.subtopics.media.destroy', [$course, $topic, $subtopic, $item]) }}"
                                  method="POST" class="hidden">
                                @csrf @method('DELETE')
                            </form>
                            @endcan
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        @endif
    </div>

    {{-- Delete Confirmation Modal --}}
    <div x-show="deleteModal.open"
         x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4"
         x-transition:enter="transition ease-out duration-200"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100">
        <div class="absolute inset-0 bg-black/40" @click="deleteModal.open = false"></div>
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden z-10">
            <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-red-600 to-red-700 rounded-t-2xl">
                <h3 class="text-base font-semibold text-white flex items-center gap-2">
                    <i class="fas fa-trash"></i> Delete Media File
                </h3>
                <button type="button" @click="deleteModal.open = false" class="text-white/80 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
                <p class="text-sm text-gray-500 mb-3">The file will be permanently removed.</p>
                <p class="text-sm text-gray-600 mb-5">
                    Are you sure you want to delete <strong x-text="deleteModal.title"></strong>?
                </p>
                <div class="flex gap-3 justify-end">
                    <button @click="deleteModal.open = false"
                            class="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition">
                        Cancel
                    </button>
                    <button @click="submitDelete()"
                            class="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition">
                        <i class="fas fa-trash mr-1.5"></i> Delete
                    </button>
                </div>
            </div>
        </div>
    </div>

</div>
@endsection

@push('scripts')
<script>
function mediaIndex() {
    return {
        deleteModal: { open: false, id: null, title: '' },
    };
}

function confirmMediaDelete(id, title) {
    const comp = Alpine.$data(document.querySelector('[x-data]'));
    comp.deleteModal = { open: true, id, title };
}

function submitDelete() {
    const comp = Alpine.$data(document.querySelector('[x-data]'));
    const form = document.getElementById('delete-media-form-' + comp.deleteModal.id);
    if (form) form.submit();
}

// Drag-and-drop reorder
(function () {
    const tbody = document.getElementById('media-tbody');
    if (!tbody) return;

    let dragging = null;

    tbody.querySelectorAll('tr').forEach(row => {
        row.setAttribute('draggable', 'true');

        row.addEventListener('dragstart', () => {
            dragging = row;
            row.classList.add('opacity-50');
        });

        row.addEventListener('dragend', () => {
            row.classList.remove('opacity-50');
            dragging = null;
            saveOrder();
        });

        row.addEventListener('dragover', e => {
            e.preventDefault();
            if (dragging && dragging !== row) {
                const rect = row.getBoundingClientRect();
                const mid  = rect.top + rect.height / 2;
                if (e.clientY < mid) {
                    tbody.insertBefore(dragging, row);
                } else {
                    tbody.insertBefore(dragging, row.nextSibling);
                }
            }
        });
    });

    function saveOrder() {
        const order = Array.from(tbody.querySelectorAll('tr')).map((row, idx) => ({
            id: parseInt(row.dataset.id),
            sort_order: idx,
        }));

        axios.patch('{{ route('self-paced.dashboard.courses.topics.subtopics.media.reorder', [$course, $topic, $subtopic]) }}', { order }, {
            headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
        }).catch(() => {});
    }
})();
</script>
@endpush
