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

@section('title', 'Edit Question — ' . $course->title)
@section('page-title', 'Edit Exam Question')
@section('page-subtitle', $course->title)

@section('hero-actions')
    <a href="{{ route('self-paced.dashboard.exams.course-questions', $course) }}"
       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 Questions
    </a>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
<style>
    #question-editor { min-height: 160px; font-size: 14px; border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem; }
    .ql-toolbar.ql-snow { border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem; background: #f9fafb; border-color: #e5e7eb; }
    .ql-container.ql-snow { border-color: #e5e7eb; border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem; }
    .ql-editor { min-height: 140px; line-height: 1.7; color: #374151; }
    .ql-editor img { max-width: 100%; border-radius: 6px; }
    #video-dialog-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:9999; align-items:center; justify-content:center; }
    #video-dialog-overlay.active { display:flex; }
    #video-dialog { background:#fff; border-radius:12px; padding:24px; width:100%; max-width:460px; box-shadow:0 20px 60px rgba(0,0,0,.3); }
</style>
@endpush

@section('content')
<div class="max-w-3xl mx-auto" x-data="questionEditForm()">

    <nav class="flex items-center gap-2 text-xs text-gray-400 mb-4">
        <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.exams.course-questions', $course) }}" class="hover:text-indigo-600 transition">{{ Str::limit($course->title, 40) }}</a>
        <i class="fas fa-chevron-right text-[10px]"></i>
        <span class="text-gray-600 font-medium">Edit Question</span>
    </nav>

    @if($errors->any())
    <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-5">
        <div class="flex items-start gap-3">
            <i class="fas fa-exclamation-circle text-red-500 mt-0.5"></i>
            <div>
                <p class="text-sm font-semibold text-red-700 mb-1">Please fix the following errors:</p>
                <ul class="text-sm text-red-600 space-y-0.5 list-disc list-inside">
                    @foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach
                </ul>
            </div>
        </div>
    </div>
    @endif

    <form action="{{ route('self-paced.dashboard.exams.update', [$course, $question]) }}"
          method="POST" enctype="multipart/form-data" id="question-form">
        @csrf
        @method('PUT')

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-6">

            <h2 class="text-base font-semibold text-gray-800 flex items-center gap-2">
                <i class="fas fa-pencil text-amber-500"></i> Edit Question
            </h2>

            <input type="hidden" name="question_text" id="question-text-plain">
            <input type="hidden" name="question_text_html" id="question-text-html">

            {{-- ── Topic Association ── --}}
            <div>
                <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                    <i class="fas fa-bookmark text-gray-400 mr-1"></i> Course Topic
                    <span class="text-gray-400 font-normal">(optional — for grouping and reporting)</span>
                </label>
                <select name="topic_id"
                        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">
                    <option value="">— No Topic —</option>
                    @foreach($topics as $t)
                    <option value="{{ $t->id }}" {{ old('topic_id', $question->topic_id) == $t->id ? 'selected' : '' }}>
                        {{ $t->title }}
                    </option>
                    @endforeach
                </select>
            </div>

            {{-- ── Rich Question Editor ── --}}
            <div>
                <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                    <i class="fas fa-question text-gray-400 mr-1"></i> Question Text <span class="text-red-500">*</span>
                </label>
                <div id="question-editor"></div>
                @error('question_text')<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
            </div>

            {{-- ── Attach Media ── --}}
            <div class="border border-dashed border-gray-200 rounded-xl p-5 bg-gray-50/50">
                <div class="flex items-center justify-between mb-3">
                    <h3 class="text-xs font-semibold text-gray-700 flex items-center gap-2">
                        <i class="fas fa-photo-video text-purple-500"></i> Attached Media File
                    </h3>
                    <button type="button" @click="showMedia = !showMedia"
                            class="text-xs text-indigo-600 hover:text-indigo-800 font-medium transition">
                        <span x-text="showMedia ? 'Hide' : 'Manage'"></span>
                        <i class="fas fa-chevron-down text-xs ml-1 transition-transform" :class="showMedia ? 'rotate-180' : ''"></i>
                    </button>
                </div>
                <div x-show="showMedia" x-transition x-cloak class="space-y-4">
                    @if($question->hasMedia())
                    @php $iconMap = ['image'=>'fa-image text-blue-500','video'=>'fa-film text-rose-500','pdf'=>'fa-file-pdf text-red-500','presentation'=>'fa-file-powerpoint text-orange-500','excel'=>'fa-file-excel text-green-600']; @endphp
                    <div class="flex items-center gap-3 p-3 bg-white border border-gray-200 rounded-lg">
                        <i class="fas {{ $iconMap[$question->question_media_type] ?? 'fa-file text-gray-400' }} text-xl flex-shrink-0"></i>
                        <div class="flex-1 min-w-0">
                            <p class="text-sm font-medium text-gray-700 truncate">{{ $question->question_media_name }}</p>
                            <p class="text-xs text-gray-400">{{ $question->getFormattedMediaSize() }} · {{ ucfirst($question->question_media_type) }}</p>
                        </div>
                        <label class="flex items-center gap-1.5 cursor-pointer text-xs text-red-600 hover:text-red-800 font-medium">
                            <input type="checkbox" name="remove_media" value="1" class="w-3.5 h-3.5"> Remove
                        </label>
                    </div>
                    @endif
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-semibold text-gray-600 mb-1.5">{{ $question->hasMedia() ? 'Replace File' : 'Upload File' }}</label>
                            <input type="file" name="question_media" @change="previewMedia($event)"
                                   accept="image/*,video/*,.pdf,.ppt,.pptx,.xls,.xlsx,.odp,.ods"
                                   class="w-full text-sm text-gray-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100 transition">
                        </div>
                        <div x-show="mediaPreview" x-cloak>
                            <label class="block text-xs font-semibold text-gray-600 mb-1.5">New File</label>
                            <div class="bg-white border border-gray-200 rounded-lg p-3 flex items-center gap-2">
                                <i class="fas text-lg" :class="mediaIcon"></i>
                                <div class="min-w-0">
                                    <p class="text-xs font-medium text-gray-700 truncate" x-text="mediaName"></p>
                                    <p class="text-xs text-gray-400" x-text="mediaSize"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="flex items-start gap-3 p-3 bg-amber-50 border border-amber-100 rounded-lg">
                        <label class="flex items-center gap-3 cursor-pointer flex-1">
                            <div class="relative flex-shrink-0">
                                <input type="hidden" name="upload_required" value="0">
                                <input type="checkbox" name="upload_required" value="1" x-model="uploadRequired"
                                       {{ old('upload_required', $question->upload_required) ? 'checked' : '' }}
                                       class="sr-only peer">
                                <div class="w-10 h-5 bg-gray-200 peer-checked:bg-amber-500 rounded-full transition peer-focus:ring-2 peer-focus:ring-amber-300"></div>
                                <div class="absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition peer-checked:translate-x-5"></div>
                            </div>
                            <div>
                                <p class="text-xs font-semibold text-gray-700">Require learner to upload a file</p>
                                <p class="text-xs text-gray-500">Learner must download the file, complete it, and upload their response.</p>
                            </div>
                        </label>
                    </div>
                    <div x-show="uploadRequired" x-transition x-cloak>
                        <label class="block text-xs font-semibold text-gray-600 mb-1.5">Upload Instruction</label>
                        <input type="text" name="upload_label" value="{{ old('upload_label', $question->upload_label) }}"
                               class="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-300 focus:border-amber-400 transition">
                    </div>
                </div>
            </div>

            {{-- ── Answer Options ── --}}
            <div>
                <p class="text-xs font-semibold text-gray-600 mb-3"><i class="fas fa-list text-gray-400 mr-1"></i> Answer Options <span class="text-red-500">*</span></p>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    @foreach(['a'=>['A','bg-green-50 border-green-200','text-green-700'],'b'=>['B','bg-blue-50 border-blue-200','text-blue-700'],'c'=>['C','bg-purple-50 border-purple-200','text-purple-700'],'d'=>['D','bg-amber-50 border-amber-200','text-amber-700']] as $key=>[$letter,$bg,$tc])
                    <div>
                        <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                            <span class="inline-flex items-center justify-center w-5 h-5 rounded-full {{ $bg }} {{ $tc }} text-xs font-bold border mr-1">{{ $letter }}</span>
                            Option {{ $letter }} <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="option_{{ $key }}" value="{{ old('option_' . $key, $question->{'option_' . $key}) }}"
                               class="w-full px-3 py-2 text-sm border @error('option_' . $key) border-red-400 bg-red-50 @else border-gray-200 @enderror rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition">
                        @error('option_' . $key)<p class="text-red-500 text-xs mt-1">{{ $message }}</p>@enderror
                    </div>
                    @endforeach
                </div>
            </div>

            {{-- ── Answer Mode Toggle ── --}}
            <div class="p-4 bg-indigo-50 border border-indigo-100 rounded-xl">
                <label class="flex items-center gap-3 cursor-pointer">
                    <div class="relative flex-shrink-0">
                        <input type="hidden" name="allow_multiple_answers" value="0">
                        <input type="checkbox" name="allow_multiple_answers" value="1"
                               x-model="multiAnswer"
                               {{ old('allow_multiple_answers', $question->allow_multiple_answers) ? 'checked' : '' }}
                               class="sr-only peer">
                        <div class="w-10 h-5 bg-gray-200 peer-checked:bg-indigo-600 rounded-full transition peer-focus:ring-2 peer-focus:ring-indigo-300"></div>
                        <div class="absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition peer-checked:translate-x-5"></div>
                    </div>
                    <div>
                        <p class="text-xs font-semibold text-gray-700">Allow multiple correct answers</p>
                        <p class="text-xs text-gray-500">Learner must select all correct options to get the mark.</p>
                    </div>
                </label>
            </div>

            {{-- ── Correct Answer — single ── --}}
            <div x-show="!multiAnswer">
                <label class="block text-xs font-semibold text-gray-600 mb-2">
                    <i class="fas fa-check-circle text-gray-400 mr-1"></i> Correct Answer <span class="text-red-500">*</span>
                </label>
                <div class="flex flex-wrap gap-3">
                    @foreach(['A','B','C','D'] as $letter)
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="radio" name="correct_answer" value="{{ $letter }}"
                               {{ old('correct_answer', $question->correct_answer) === $letter ? 'checked' : '' }}
                               class="w-4 h-4 text-indigo-600 border-gray-300 focus:ring-indigo-500">
                        <span class="text-sm font-medium text-gray-700">Option {{ $letter }}</span>
                    </label>
                    @endforeach
                </div>
            </div>

            {{-- ── Correct Answers — multi ── --}}
            <div x-show="multiAnswer" x-cloak>
                <label class="block text-xs font-semibold text-gray-600 mb-2">
                    <i class="fas fa-check-double text-gray-400 mr-1"></i> Correct Answers
                    <span class="text-gray-400 font-normal">(select all that apply)</span>
                    <span class="text-red-500">*</span>
                </label>
                <div class="flex flex-wrap gap-3">
                    @php $existingMulti = old('correct_answers_json', $question->correct_answers_json ?? []); @endphp
                    @foreach(['A','B','C','D'] as $letter)
                    <label class="flex items-center gap-2 cursor-pointer px-3 py-2 rounded-lg border-2 border-gray-200 hover:border-indigo-300 hover:bg-indigo-50/40 transition has-[:checked]:border-indigo-500 has-[:checked]:bg-indigo-50">
                        <input type="checkbox" name="correct_answers_json[]" value="{{ $letter }}"
                               {{ in_array($letter, $existingMulti) ? 'checked' : '' }}
                               class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                        <span class="text-sm font-semibold text-gray-700">Option {{ $letter }}</span>
                    </label>
                    @endforeach
                </div>
                <p class="text-xs text-gray-400 mt-1.5"><i class="fas fa-info-circle mr-1"></i> Learner must select exactly these options to score the mark.</p>
            </div>

            {{-- ── Explanation ── --}}
            <div>
                <label class="block text-xs font-semibold text-gray-600 mb-1.5">
                    <i class="fas fa-lightbulb text-gray-400 mr-1"></i> Explanation <span class="text-gray-400 font-normal">(optional)</span>
                </label>
                <textarea name="explanation" rows="2"
                          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 resize-none">{{ old('explanation', $question->explanation) }}</textarea>
            </div>

            {{-- ── Sort Order & Active ── --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                <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', $question->sort_order) }}" 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">
                </div>
                <div class="flex items-end pb-1">
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" name="is_active" value="1"
                               {{ old('is_active', $question->is_active) ? 'checked' : '' }}
                               class="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                        <span class="text-sm font-medium text-gray-700"><i class="fas fa-toggle-on text-gray-400 mr-1"></i> Active</span>
                    </label>
                </div>
            </div>

        </div>

        <div class="flex justify-between mt-4">
            <a href="{{ route('self-paced.dashboard.exams.course-questions', $course) }}"
               class="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-semibold rounded-lg transition">
                <i class="fas fa-arrow-left"></i> Cancel
            </a>
            <button type="submit"
                    class="inline-flex items-center gap-2 px-6 py-2.5 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg transition shadow">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </div>

    </form>
</div>

<div id="video-dialog-overlay">
    <div id="video-dialog">
        <h3 class="text-sm font-semibold text-gray-800 mb-1 flex items-center gap-2"><i class="fas fa-video text-indigo-500"></i> Embed Video</h3>
        <p class="text-xs text-gray-500 mb-3">Paste a YouTube, Vimeo, or direct video URL.</p>
        <input type="text" id="video-url-input" placeholder="https://www.youtube.com/watch?v=..."
               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 mb-3">
        <div class="flex gap-2 justify-end">
            <button type="button" id="video-cancel" class="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">Cancel</button>
            <button type="button" id="video-insert" class="px-4 py-2 text-sm bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition">Insert</button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script>
function questionEditForm() {
    return {
        showMedia: {{ $question->hasMedia() ? 'true' : 'false' }},
        uploadRequired: {{ old('upload_required', $question->upload_required) ? 'true' : 'false' }},
        multiAnswer: {{ old('allow_multiple_answers', $question->allow_multiple_answers) ? 'true' : 'false' }},
        mediaPreview: false,
        mediaName: '',
        mediaSize: '',
        mediaIcon: 'fa-file text-gray-400',

        previewMedia(event) {
            const file = event.target.files[0];
            if (!file) { this.mediaPreview = false; return; }
            this.mediaPreview = true;
            this.mediaName = file.name;
            this.mediaSize = this.formatSize(file.size);
            const t = file.type;
            if (t.startsWith('video/'))       this.mediaIcon = 'fa-film text-rose-500';
            else if (t.startsWith('image/'))  this.mediaIcon = 'fa-image text-blue-500';
            else if (t === 'application/pdf') this.mediaIcon = 'fa-file-pdf text-red-500';
            else if (file.name.match(/\.pptx?$/i)) this.mediaIcon = 'fa-file-powerpoint text-orange-500';
            else if (file.name.match(/\.xlsx?$|\.csv$/i)) this.mediaIcon = 'fa-file-excel text-green-600';
            else this.mediaIcon = 'fa-file text-gray-400';
        },

        formatSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / 1048576).toFixed(2) + ' MB';
        }
    };
}

(function () {
    const overlay  = document.getElementById('video-dialog-overlay');
    const urlInput = document.getElementById('video-url-input');
    let quillRange = null;

    function openVideoDialog(range) {
        quillRange = range;
        urlInput.value = '';
        overlay.classList.add('active');
        setTimeout(() => urlInput.focus(), 50);
    }

    document.getElementById('video-cancel').addEventListener('click', () => overlay.classList.remove('active'));
    overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.classList.remove('active'); });

    document.getElementById('video-insert').addEventListener('click', () => {
        const url = urlInput.value.trim();
        if (!url) return;
        overlay.classList.remove('active');
        let embedUrl = url;
        const yt = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([A-Za-z0-9_-]{11})/);
        if (yt) embedUrl = 'https://www.youtube.com/embed/' + yt[1];
        const vm = url.match(/vimeo\.com\/(\d+)/);
        if (vm) embedUrl = 'https://player.vimeo.com/video/' + vm[1];
        const index = quillRange ? quillRange.index : quill.getLength();
        quill.insertEmbed(index, 'video', embedUrl, 'user');
        quill.setSelection(index + 1, 0);
    });

    function imageUploadHandler() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();
        input.onchange = async () => {
            const file = input.files[0];
            if (!file) return;
            const fd = new FormData();
            fd.append('file', file);
            fd.append('_token', document.querySelector('meta[name="csrf-token"]').content);
            try {
                const res = await fetch('{{ route("api.self-paced.media.upload") }}', { method: 'POST', body: fd });
                const data = await res.json();
                if (res.ok && data.location) {
                    const range = quill.getSelection(true);
                    quill.insertEmbed(range.index, 'image', data.location, 'user');
                    quill.setSelection(range.index + 1, 0);
                } else {
                    alert(data.error || 'Image upload failed. Please try again.');
                }
            } catch (e) { alert('Image upload failed. Please check your connection and try again.'); }
        };
    }

    const quill = new Quill('#question-editor', {
        theme: 'snow',
        placeholder: 'Type the question here…',
        modules: {
            toolbar: {
                container: [
                    [{ 'header': [1, 2, 3, false] }],
                    ['bold', 'italic', 'underline'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                    ['blockquote', 'code-block'],
                    ['link', 'image', 'video'],
                    ['clean'],
                ],
                handlers: {
                    image: imageUploadHandler,
                    video: function () { openVideoDialog(this.quill.getSelection()); },
                },
            },
        },
    });

    // Load existing content
    const existing = {!! json_encode(old('question_text_html', $question->question_text_html ?? $question->question_text)) !!};
    if (existing) quill.clipboard.dangerouslyPasteHTML(existing);

    document.getElementById('question-form').addEventListener('submit', function () {
        document.getElementById('question-text-plain').value = quill.getText().trim();
        document.getElementById('question-text-html').value  = quill.getSemanticHTML();
    });
})();
</script>
@endpush
