<template>
  <div class="p-6 max-w-4xl mx-auto">
    <!-- Loading -->
    <div v-if="loading" class="text-center py-12">
      <q-spinner size="lg" color="primary" />
      <p class="mt-4">กำลังโหลด...</p>
    </div>

    <!-- Content -->
    <div v-else-if="lesson">
      <!-- Header -->
      <div class="flex items-center gap-4 mb-6">
        <q-btn
          flat
          round
          icon="arrow_back"
          @click="navigateTo(`/instructor/courses/${courseId}/structure`)"
        />
        <div>
          <h1 class="text-2xl font-bold">แก้ไขบทเรียน (วิดีโอ)</h1>
          <p class="text-gray-500">{{ lesson.title.th }}</p>
        </div>
      </div>

      <!-- Form -->
      <q-card>
        <q-card-section>
          <div class="space-y-4">
            <!-- Title Thai -->
            <q-input
              v-model="form.title.th"
              label="ชื่อบทเรียน (ภาษาไทย) *"
              outlined
              :rules="[val => !!val || 'กรุณากรอกชื่อบทเรียน']"
              lazy-rules="ondemand"
              hide-bottom-space
            />

            <!-- Title English -->
            <q-input
              v-model="form.title.en"
              label="ชื่อบทเรียน (English)"
              outlined
            />

            <!-- Content Thai -->
            <q-input
              v-model="form.content.th"
              label="คำอธิบาย (ภาษาไทย)"
              type="textarea"
              outlined
              autogrow
              rows="3"
            />

            <!-- Content English -->
            <q-input
              v-model="form.content.en"
              label="คำอธิบาย (English)"
              type="textarea"
              outlined
              autogrow
              rows="3"
            />
            <q-card-section class="flex justify-end gap-2">
          <q-btn
            flat
            label="ยกเลิก"
            @click="navigateTo(`/instructor/courses/${courseId}/structure`)"
          />
          <q-btn
            color="primary"
            label="บันทึก"
            icon="save"
            :loading="saving"
            @click="saveLesson"
          />
        </q-card-section>
          </div>
        </q-card-section>

        <!-- Video Section -->
        <q-separator />
        <q-card-section>
          <h3 class="text-lg font-semibold mb-4">วิดีโอ</h3>
          
          <!-- Current Video -->
          <div v-if="lesson.video_url" class="mb-6">
            <p class="text-sm text-gray-500 mb-2">วิดีโอปัจจุบัน:</p>
            <div v-if="isYoutubeUrl(lesson.video_url)" class="aspect-video w-full max-w-xl rounded-lg overflow-hidden bg-black">
              <iframe 
                :src="getEmbedUrl(lesson.video_url)" 
                width="100%" 
                height="100%" 
                frameborder="0" 
                allowfullscreen
              ></iframe>
            </div>
            <video 
              v-else
              :src="lesson.video_url" 
              controls 
              class="w-full max-w-xl rounded-lg"
            />
          </div>

          <div class="mb-4">
            <q-tabs
              v-model="videoSourceType"
              dense
              class="text-grey"
              active-color="primary"
              indicator-color="primary"
              align="left"
              narrow-indicator
            >
              <q-tab name="upload" label="อัพโหลดไฟล์" />
              <q-tab name="youtube" label="YouTube" />
            </q-tabs>
            <q-separator />
          </div>

          <!-- Upload New Video -->
          <div v-if="videoSourceType === 'upload'">
            <div 
              class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-primary hover:bg-primary/5 transition-colors"
              @click="triggerVideoInput"
              @dragover.prevent
              @drop.prevent="handleVideoDrop"
            >
              <input
                ref="videoInput"
                type="file"
                accept="video/mp4,video/webm"
                class="hidden"
                @change="handleVideoSelect"
              />
              <div v-if="selectedVideo">
                <q-icon name="videocam" size="48px" color="primary" />
                <p class="mt-2 font-medium">{{ selectedVideo.name }}</p>
                <p class="text-sm text-gray-400">{{ formatFileSize(selectedVideo.size) }}</p>
                <q-btn
                  class="mt-2"
                  flat
                  size="sm"
                  color="negative"
                  label="ลบ"
                  icon="close"
                  @click.stop="selectedVideo = null"
                />
              </div>
              <div v-else>
                <q-icon name="cloud_upload" size="48px" color="grey" />
                <p class="mt-2 text-gray-500">ลากไฟล์มาวางที่นี่ หรือคลิกเพื่อเลือกไฟล์</p>
                <p class="text-sm text-gray-400">รองรับ MP4, WebM (สูงสุด 500 MB)</p>
                <q-btn
                  class="mt-4"
                  color="primary"
                  outline
                  label="เลือกไฟล์วิดีโอ"
                  icon="upload"
                />
              </div>
            </div>
            
            <!-- Upload Button -->
            <div v-if="selectedVideo" class="mt-4 text-center">
              <q-btn
                color="primary"
                label="อัพโหลดวิดีโอ"
                icon="cloud_upload"
                :loading="uploadingVideo"
                @click="uploadVideo"
              />
            </div>
          </div>

          <!-- YouTube Input -->
          <div v-else class="max-w-xl">
             <q-input
              v-model="youtubeUrl"
              label="YouTube URL"
              hint="ตัวอย่าง: https://www.youtube.com/watch?v=..."
              outlined
              class="mb-4"
            />
            <q-btn
              color="primary"
              label="บันทึก YouTube Video"
              icon="save"
              :loading="savingYoutube"
              @click="saveYoutubeVideo"
              :disable="!isValidYoutubeUrl"
            />
          </div>

        </q-card-section>
        
        <!-- Prerequisite Settings Section -->
        <q-separator />
        <q-card-section>
          <h3 class="text-lg font-semibold mb-4">การตั้งค่าลำดับบทเรียน</h3>
          <div class="space-y-4">
            <q-select
              v-model="prerequisiteSettings.prerequisite_lesson_ids"
              :options="availableLessons"
              option-value="id"
              option-label="label"
              emit-value
              map-options
              multiple
              use-chips
              filled
              label="บทเรียนที่ต้องเรียนก่อน"
              hint="เลือกบทเรียนที่ต้องเรียนก่อนหน้าจึงจะปลดล็อคบทเรียนนี้"
            >
              <template v-slot:option="{ opt, itemProps }">
                <q-item v-bind="itemProps">
                  <q-item-section>
                    <q-item-label>{{ opt.label }}</q-item-label>
                    <q-item-label caption>{{ opt.chapterTitle }}</q-item-label>
                  </q-item-section>
                </q-item>
              </template>
            </q-select>

            <div class="text-right">
              <q-btn
                color="primary"
                label="บันทึกการตั้งค่า"
                icon="save"
                :loading="savingPrerequisite"
                @click="savePrerequisiteSettings"
              />
            </div>
          </div>
        </q-card-section>

        <!-- Attachments Section -->
        <q-separator />
        <q-card-section>
          <h3 class="text-lg font-semibold mb-4">ไฟล์แนบ</h3>
          
          <!-- Attachments List -->
          <div v-if="lesson.attachments && lesson.attachments.length > 0" class="space-y-2 mb-4">
            <div 
              v-for="attachment in visibleAttachments" 
              :key="attachment.id"
              class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg"
            >
              <q-icon name="attach_file" color="grey" />
              <div class="flex-1">
                <p class="font-medium">{{ attachment.file_name }}</p>
                <p class="text-sm text-gray-500">{{ formatFileSize(attachment.file_size) }}</p>
              </div>
              <q-btn 
                flat 
                round 
                icon="delete" 
                color="negative" 
                size="sm"
                :loading="deletingAttachmentId === attachment.id"
                @click="deleteAttachment(attachment.id)"
              />
            </div>
          </div>

          <input
            :ref="(el: any) => attachmentInput = el"
            type="file"
            multiple
            class="hidden"
            @change="handleAttachmentSelect"
          />
          <q-btn
            outline
            color="primary"
            icon="add"
            label="เพิ่มไฟล์แนบ"
            :loading="uploadingAttachment"
            @click="triggerAttachmentInput"
          />
        </q-card-section>

        <!-- Actions -->
        <q-separator />
        
      </q-card>
    </div>

    <!-- Error -->
    <div v-else class="text-center py-12">
      <q-icon name="error" size="48px" color="negative" />
      <p class="mt-4 text-gray-500">ไม่พบบทเรียน</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import { instructorService, type LessonResponse } from '~/services/instructor.service';

const route = useRoute();
const $q = useQuasar();

const courseId = Number(route.params.id);
const chapterId = Number(route.params.chapterId);
const lessonId = Number(route.params.lessonId);

const loading = ref(true);
const saving = ref(false);
const lesson = ref<LessonResponse | null>(null);

const visibleAttachments = computed(() => {
  if (!lesson.value?.attachments) return [];
  return lesson.value.attachments.filter(a => !a.mime_type.includes('video'));
});

const form = ref({
  title: { th: '', en: '' },
  content: { th: '', en: '' }
});

// Prerequisite settings
const prerequisiteSettings = ref({
  prerequisite_lesson_ids: [] as number[]
});
const savingPrerequisite = ref(false);

interface LessonOption {
  id: number;
  label: string;
  chapterTitle: string;
}
const allLessonsInCourse = ref<LessonOption[]>([]);

const availableLessons = computed(() => {
  // Filter out current lesson from available options
  return allLessonsInCourse.value.filter(l => l.id !== lessonId);
});

const selectedVideo = ref<File | null>(null);
const uploadingVideo = ref(false);
const videoInput = ref<HTMLInputElement | null>(null);

// YouTube Support
const videoSourceType = ref('upload');
const youtubeUrl = ref('');
const savingYoutube = ref(false);

const youtubeRegex = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;

const isYoutubeUrl = (url: string) => {
  return youtubeRegex.test(url);
};

const getEmbedUrl = (url: string) => {
  const match = url.match(youtubeRegex);
  if (match && match[1]) {
    return `https://www.youtube.com/embed/${match[1]}`;
  }
  return url;
};

const fetchYoutubeTitle = async (url: string) => {
  try {
    const response = await fetch(`https://noembed.com/embed?url=${url}`);
    const data = await response.json();
    if (data.title) {
      return data.title;
    }
  } catch (error) {
    console.warn('Failed to fetch YouTube title:', error);
  }
  return '';
};

const isValidYoutubeUrl = computed(() => {
  return youtubeRegex.test(youtubeUrl.value);
});

// Watch for YouTube URL changes to fetch title
watch(youtubeUrl, async (newUrl) => {
  if (isValidYoutubeUrl.value) {
    const title = await fetchYoutubeTitle(newUrl);
    if (title && !form.value.title.th) {
       // Autocomplete lesson title if empty
       form.value.title.th = title;
    }
    // We could store it to use as video_title specifically, 
    // but for now let's rely on form.title.th or the fetched title for the API call validation if we want to be strict.
    // However, the user probably wants the 'video_title' passed to backend to be correct.
    // Let's store it.
    fetchedVideoTitle.value = title;
  } else {
    fetchedVideoTitle.value = '';
  }
});

const fetchedVideoTitle = ref('');

const saveYoutubeVideo = async () => {
  if (!isValidYoutubeUrl.value) return;

  const match = youtubeUrl.value.match(youtubeRegex);
  if (!match || !match[1]) return;

  const videoId = match[1];
  savingYoutube.value = true;
  
  try {
    // If we have a fetched title, we can genericallly use it, or fallback to lesson title
    const videoTitle = fetchedVideoTitle.value || form.value.title.th || 'Untitled Video';

    const response = await instructorService.setLessonYoutubeVideo(
      courseId, 
      chapterId, 
      lessonId, 
      videoId, 
      videoTitle
    );
    
    // If lesson title is empty, update it too
    if (!form.value.title.th && fetchedVideoTitle.value) {
       form.value.title.th = fetchedVideoTitle.value;
       // We might want to save the lesson title change as well? 
       // The current flow saves video separately. 
       // Let's just update the local form for now, user can click "Save" on the form if they want to persist the name change to the lesson itself.
    }

    $q.notify({ type: 'positive', message: response.message || 'บันทึกวิดีโอ YouTube สำเร็จ', position: 'top' });
    youtubeUrl.value = '';
    fetchedVideoTitle.value = '';
    await fetchLesson();
  } catch (error) {
    console.error('Failed to save YouTube video:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถบันทึกวิดีโอได้', position: 'top' });
  } finally {
    savingYoutube.value = false;
  }
};

const triggerVideoInput = () => {
  videoInput.value?.click();
};

const fetchLesson = async () => {
  loading.value = true;
  try {
    const data = await instructorService.getLesson(courseId, chapterId, lessonId);
    lesson.value = data;
    form.value = {
      title: { ...data.title },
      content: data.content ? { ...data.content } : { th: '', en: '' }
    };
    
    // Check if current video is YouTube
    if (data.video_url && isYoutubeUrl(data.video_url)) {
      videoSourceType.value = 'youtube';
      youtubeUrl.value = data.video_url;
    } else {
      videoSourceType.value = 'upload';
    }

    // Load prerequisite settings
    prerequisiteSettings.value = {
      prerequisite_lesson_ids: data.prerequisite_lesson_ids || []
    };
    
    // Fetch all lessons in course for prerequisite selection
    const courseData = await instructorService.getCourseById(courseId);
    const lessonsOptions: LessonOption[] = [];
    courseData.chapters.forEach(chapter => {
      chapter.lessons.forEach(l => {
        lessonsOptions.push({
          id: l.id,
          label: l.title.th || l.title.en,
          chapterTitle: chapter.title.th || chapter.title.en
        });
      });
    });
    allLessonsInCourse.value = lessonsOptions;
  } catch (error) {
    console.error('Failed to fetch lesson:', error);
    $q.notify({ type: 'negative', message: 'ไม่สามารถโหลดข้อมูลได้', position: 'top' });
  } finally {
    loading.value = false;
  }
};

const savePrerequisiteSettings = async () => {
  savingPrerequisite.value = true;
  try {
    const response = await instructorService.updateLesson(courseId, chapterId, lessonId, {
      ...form.value,
      prerequisite_lesson_ids: prerequisiteSettings.value.prerequisite_lesson_ids.length > 0 
        ? prerequisiteSettings.value.prerequisite_lesson_ids 
        : null
    });
    $q.notify({ type: 'positive', message: response.message || 'บันทึกการตั้งค่าสำเร็จ', position: 'top' });
  } catch (error) {
    console.error('Failed to save prerequisite settings:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถบันทึกได้', position: 'top' });
  } finally {
    savingPrerequisite.value = false;
  }
};

const saveLesson = async () => {
  saving.value = true;
  try {
    const response = await instructorService.updateLesson(courseId, chapterId, lessonId, form.value);
    $q.notify({ type: 'positive', message: response.message, position: 'top' });
    navigateTo(`/instructor/courses/${courseId}/structure`);
  } catch (error) {
    console.error('Failed to save lesson:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถบันทึกได้', position: 'top' });
  } finally {
    saving.value = false;
  }
};

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};

const handleVideoSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files[0]) {
    const file = target.files[0];
    if (file.size > 500 * 1024 * 1024) {
      $q.notify({ type: 'warning', message: 'ขนาดไฟล์เกิน 500 MB', position: 'top' });
      return;
    }
    selectedVideo.value = file;
  }
};

const handleVideoDrop = (event: DragEvent) => {
  if (event.dataTransfer?.files && event.dataTransfer.files[0]) {
    const file = event.dataTransfer.files[0];
    if (!['video/mp4', 'video/webm'].includes(file.type)) {
      $q.notify({ type: 'warning', message: 'รองรับเฉพาะ MP4 และ WebM', position: 'top' });
      return;
    }
    if (file.size > 500 * 1024 * 1024) {
      $q.notify({ type: 'warning', message: 'ขนาดไฟล์เกิน 500 MB', position: 'top' });
      return;
    }
    selectedVideo.value = file;
  }
};

const uploadVideo = async () => {
  if (!selectedVideo.value) return;
  
  uploadingVideo.value = true;
  try {
    let response;
    if (lesson.value?.video_url) {
      response = await instructorService.updateLessonVideo(courseId, chapterId, lessonId, selectedVideo.value);
    } else {
      response = await instructorService.uploadLessonVideo(courseId, chapterId, lessonId, selectedVideo.value);
    }
    $q.notify({ type: 'positive', message: response.message, position: 'top' });
    selectedVideo.value = null;
    await fetchLesson();
  } catch (error) {
    console.error('Failed to upload video:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถอัพโหลดวิดีโอได้', position: 'top' });
  } finally {
    uploadingVideo.value = false;
  }
};

// Attachment functions
const attachmentInput = ref<HTMLInputElement | null>(null);
const uploadingAttachment = ref(false);
const deletingAttachmentId = ref<number | null>(null);

const triggerAttachmentInput = () => {
  console.log('Trigger attachment input:', attachmentInput.value);
  attachmentInput.value?.click();
};

const handleAttachmentSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const files = Array.from(target.files);
    uploadingAttachment.value = true;
    try {
      const response = await instructorService.addAttachments(courseId, chapterId, lessonId, files);
      $q.notify({ type: 'positive', message: response.message, position: 'top' });
      await fetchLesson();
    } catch (error) {
      console.error('Failed to upload attachments:', error);
      $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถอัพโหลดไฟล์แนบได้', position: 'top' });
    } finally {
      uploadingAttachment.value = false;
      target.value = '';
    }
  }
};

const deleteAttachment = async (attachmentId: number) => {
  deletingAttachmentId.value = attachmentId;
  try {
    const response = await instructorService.deleteAttachment(courseId, chapterId, lessonId, attachmentId);
    $q.notify({ type: 'positive', message: response.message, position: 'top' });
    await fetchLesson();
  } catch (error) {
    console.error('Failed to delete attachment:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถลบไฟล์แนบได้', position: 'top' });
  } finally {
    deletingAttachmentId.value = null;
  }
};

onMounted(() => {
  fetchLesson();
});
</script>
