<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 class="mb-6">
        <q-card-section>
          <h3 class="text-lg font-semibold mb-4">ข้อมูลทั่วไป</h3>
          <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="2"
            />

            <!-- Content English -->
            <q-input
              v-model="form.content.en"
              label="คำอธิบาย (English)"
              type="textarea"
              outlined
              autogrow
              rows="2"
            />
          </div>
        </q-card-section>

        <!-- Actions -->
        <q-separator />
        <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>
      </q-card>

      <!-- Quiz Settings -->
      <q-card class="mb-6">
        <q-card-section>
          <h3 class="text-lg font-semibold mb-4">ตั้งค่าแบบทดสอบ</h3>
          <div class="grid grid-cols-2 gap-4">
            <q-input
              v-model.number="quizSettings.passing_score"
              label="คะแนนผ่าน (%)"
              type="number"
              outlined
              min="0"
              max="100"
            />
            <q-input
              v-model.number="quizSettings.time_limit"
              label="เวลาจำกัด (นาที)"
              type="number"
              outlined
              min="0"
              hint="0 = ไม่จำกัดเวลา"
            />
            <q-toggle
              v-model="quizSettings.shuffle_questions"
              label="สุ่มลำดับคำถาม"
            />
            <q-toggle
              v-model="quizSettings.shuffle_choices"
              label="สุ่มลำดับตัวเลือก"
            />
            <q-toggle
              v-model="quizSettings.show_answers_after_completion"
              label="แสดงเฉลยหลังทำเสร็จ"
            />
            <q-toggle
              v-model="quizSettings.is_skippable"
              label="ทำแบบทดสอบข้ามได้"
            />
          </div>
          <div class="mt-4 text-right">
            <q-btn
              color="primary"
              label="บันทึกการตั้งค่า"
              icon="save"
              :loading="savingSettings"
              @click="saveQuizSettings"
            />
          </div>
        </q-card-section>
      </q-card>

      <!-- Prerequisite Settings -->
      <q-card class="mb-6">
        <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>
      </q-card>

      <!-- Questions -->
      <q-card>
        <q-card-section>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">คำถาม ({{ questions.length }} ข้อ)</h3>
            <q-btn
              color="primary"
              icon="add"
              label="เพิ่มคำถาม"
              @click="addQuestion"
            />
          </div>

          <!-- Questions List -->
          <draggable
            v-if="questions.length > 0"
            v-model="questions"
            item-key="id"
            handle=".drag-handle"
            animation="200"
            ghost-class="opacity-50"
            class="space-y-4"
            @end="onDragEnd"
          >
            <template #item="{ element: question, index: qIndex }">
              <q-card flat bordered class="bg-gray-50">
                <q-card-section>
                  <div class="flex justify-between items-start mb-3">
                    <div class="flex items-center gap-2">
                      <q-icon 
                        name="drag_indicator" 
                        class="drag-handle cursor-grab text-gray-400 hover:text-gray-600"
                        size="20px"
                      />
                      <span class="font-medium">คำถามที่ {{ qIndex + 1 }}</span>
                    </div>
                    <div class="flex gap-1">
                      <q-btn flat round dense icon="edit" size="sm" @click="editQuestion(qIndex)" />
                      <q-btn flat round dense icon="delete" color="negative" size="sm" @click="removeQuestion(qIndex)" />
                    </div>
                  </div>
                  <p class="mb-2">{{ question.text.th || '(ยังไม่ได้กรอกคำถาม)' }}</p>
                  
                  <!-- Choices Preview -->
                  <div class="pl-4 space-y-1">
                    <div 
                      v-for="(choice, cIndex) in question.choices" 
                      :key="cIndex"
                      class="flex items-center gap-2 text-sm"
                    >
                      <q-icon 
                        :name="choice.is_correct ? 'check_circle' : 'radio_button_unchecked'"
                        :color="choice.is_correct ? 'positive' : 'grey'"
                        size="18px"
                      />
                      <span :class="{ 'text-green-600 font-medium': choice.is_correct }">
                        {{ choice.text.th || `ตัวเลือก ${Number(cIndex) + 1}` }}
                      </span>
                    </div>
                  </div>
                </q-card-section>
              </q-card>
            </template>
          </draggable>

          <!-- Empty State -->
          <div v-else class="text-center py-8 text-gray-500">
            <q-icon name="quiz" size="48px" color="grey" />
            <p class="mt-2">ยังไม่มีคำถาม</p>
            <p class="text-sm">คลิก "เพิ่มคำถาม" เพื่อเริ่มสร้างแบบทดสอบ</p>
          </div>
        </q-card-section>
      </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>

    <!-- Question Dialog -->
    <q-dialog v-model="questionDialog" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <h3 class="text-lg font-semibold">{{ editingQuestionIndex !== null ? 'แก้ไขคำถาม' : 'เพิ่มคำถาม' }}</h3>
        </q-card-section>

        <q-separator />

        <q-card-section class="space-y-4">
          <q-input
            v-model="questionForm.text.th"
            label="คำถาม (ภาษาไทย) *"
            outlined
            autogrow
          />
          <q-input
            v-model="questionForm.text.en"
            label="คำถาม (English)"
            outlined
            autogrow
          />

          <div class="border-t pt-4 mt-4">
            <div class="flex justify-between items-center mb-2">
              <span class="font-medium">ตัวเลือก</span>
              <q-btn flat size="sm" icon="add" label="เพิ่มตัวเลือก" @click="addChoice" />
            </div>
            
            <div class="space-y-3">
              <div 
                v-for="(choice, cIndex) in questionForm.choices" 
                :key="cIndex"
                class="flex items-start gap-2"
              >
                <q-radio
                  :model-value="getCorrectIndex()"
                  :val="cIndex"
                  @update:model-value="setCorrectChoice(cIndex)"
                />
                <q-input
                  v-model="choice.text.th"
                  :label="`ตัวเลือก ${cIndex + 1}`"
                  outlined
                  dense
                  class="flex-1"
                />
                <q-btn
                  v-if="questionForm.choices.length > 2"
                  flat
                  round
                  dense
                  icon="close"
                  color="negative"
                  @click="removeChoice(cIndex)"
                />
              </div>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section class="flex justify-end gap-2">
          <q-btn flat label="ยกเลิก" @click="questionDialog = false" :disable="savingQuestion" />
          <q-btn color="primary" label="บันทึก" @click="saveQuestion" :loading="savingQuestion" />
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import draggable from 'vuedraggable';
import { instructorService, type LessonResponse, type CreateQuestionRequest } 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 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(() => {
  return allLessonsInCourse.value.filter(l => l.id !== lessonId);
});

const quizSettings = ref({
  passing_score: 60,
  time_limit: 0,
  shuffle_questions: false,
  shuffle_choices: false,
  show_answers_after_completion: true,
  is_skippable: false
});

const savingSettings = ref(false);

const saveQuizSettings = async () => {
  savingSettings.value = true;
  try {
    const response = await instructorService.updateQuizSettings(courseId, chapterId, lessonId, {
      title: form.value.title,
      description: form.value.content,
      passing_score: quizSettings.value.passing_score,
      time_limit: quizSettings.value.time_limit,
      shuffle_questions: quizSettings.value.shuffle_questions,
      shuffle_choices: quizSettings.value.shuffle_choices,
      show_answers_after_completion: quizSettings.value.show_answers_after_completion,
      is_skippable: quizSettings.value.is_skippable
    });
    $q.notify({ type: 'positive', message: response.message, position: 'top' });
  } catch (error) {
    console.error('Failed to save quiz settings:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถบันทึกการตั้งค่าได้', position: 'top' });
  } finally {
    savingSettings.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;
  }
};

// Drag and Drop handler (vuedraggable)
const onDragEnd = async (event: { oldIndex: number; newIndex: number }) => {
  const { oldIndex, newIndex } = event;
  if (oldIndex === newIndex) return;
  
  const question = questions.value[newIndex];
  if (!question.id) return;
  
  try {
    // Call API with new position (1-indexed)
    const response = await instructorService.reorderQuestion(courseId, chapterId, lessonId, question.id, newIndex + 1);
    $q.notify({ type: 'positive', message: response.message, position: 'top' });
  } catch (error) {
    console.error('Failed to reorder question:', error);
    // Revert on error - swap back
    const [item] = questions.value.splice(newIndex, 1);
    questions.value.splice(oldIndex, 0, item);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถเรียงลำดับได้', position: 'top' });
  }
};

interface QuizChoice {
  id?: number;
  text: { th: string; en: string };
  is_correct: boolean;
}

interface QuizQuestion {
  id?: number;
  text: { th: string; en: string };
  choices: QuizChoice[];
}

const questions = ref<QuizQuestion[]>([]);
const questionDialog = ref(false);
const editingQuestionIndex = ref<number | null>(null);
const questionForm = ref<QuizQuestion>({
  text: { th: '', en: '' },
  choices: [
    { text: { th: '', en: '' }, is_correct: true },
    { text: { th: '', en: '' }, is_correct: false }
  ]
});

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: '' }
    };
    
    // 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;
    
    // Load quiz settings
    if (data.quiz) {
      quizSettings.value = {
        passing_score: data.quiz.passing_score || 60,
        time_limit: data.quiz.time_limit || 0,
        shuffle_questions: data.quiz.shuffle_questions || false,
        shuffle_choices: data.quiz.shuffle_choices || false,
        show_answers_after_completion: data.quiz.show_answers_after_completion !== false,
        is_skippable: data.quiz.is_skippable || false
      };
      
      // Load questions from API
      if (data.quiz.questions) {
        questions.value = data.quiz.questions.map(q => ({
          id: q.id,
          text: { th: q.question.th, en: q.question.en },
          choices: q.choices.map(c => ({
            id: c.id,
            text: { th: c.text.th, en: c.text.en },
            is_correct: c.is_correct
          }))
        }));
      }
    }
  } catch (error) {
    console.error('Failed to fetch lesson:', error);
    $q.notify({ type: 'negative', message: 'ไม่สามารถโหลดข้อมูลได้', position: 'top' });
  } finally {
    loading.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 addQuestion = () => {
  editingQuestionIndex.value = null;
  questionForm.value = {
    text: { th: '', en: '' },
    choices: [
      { text: { th: '', en: '' }, is_correct: true },
      { text: { th: '', en: '' }, is_correct: false }
    ]
  };
  questionDialog.value = true;
};

const editQuestion = (index: number) => {
  editingQuestionIndex.value = index;
  questionForm.value = JSON.parse(JSON.stringify(questions.value[index]));
  questionDialog.value = true;
};

const removeQuestion = async (index: number) => {
  const question = questions.value[index];
  $q.dialog({
    title: 'ยืนยันการลบ',
    message: 'ต้องการลบคำถามนี้หรือไม่?',
    cancel: true,
    persistent: true
  }).onOk(async () => {
    try {
      if (question.id) {
        const response = await instructorService.deleteQuestion(courseId, chapterId, lessonId, question.id);
        $q.notify({ type: 'positive', message: response.message, position: 'top' });
      } else {
        $q.notify({ type: 'positive', message: 'ลบคำถามสำเร็จ', position: 'top' });
      }
      questions.value.splice(index, 1);
    } catch (error) {
      console.error('Failed to delete question:', error);
      $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถลบคำถามได้', position: 'top' });
    }
  });
};

const savingQuestion = ref(false);

const saveQuestion = async () => {
  if (!questionForm.value.text.th) {
    $q.notify({ type: 'warning', message: 'กรุณากรอกคำถาม', position: 'top' });
    return;
  }

  savingQuestion.value = true;
  try {
    const questionData: CreateQuestionRequest = {
      question: questionForm.value.text,
      explanation: { th: '', en: '' },
      question_type: 'MULTIPLE_CHOICE',
      sort_order: editingQuestionIndex.value !== null 
        ? questions.value[editingQuestionIndex.value].id ? editingQuestionIndex.value + 1 : questions.value.length + 1
        : questions.value.length + 1,
      choices: questionForm.value.choices.map((c, i) => ({
        text: c.text,
        is_correct: c.is_correct,
        sort_order: i + 1
      }))
    };
    
    console.log('Saving question:', JSON.stringify(questionData, null, 2));

    if (editingQuestionIndex.value !== null && questions.value[editingQuestionIndex.value].id) {
      // Update existing question
      const response = await instructorService.updateQuestion(
        courseId, chapterId, lessonId, 
        questions.value[editingQuestionIndex.value].id!, 
        questionData
      );
      $q.notify({ type: 'positive', message: response.message, position: 'top' });
    } else {
      // Create new question
      const response = await instructorService.createQuestion(courseId, chapterId, lessonId, questionData);
      $q.notify({ type: 'positive', message: response.message, position: 'top' });
    }
    
    questionDialog.value = false;
    // Refresh data
    await fetchLesson();
  } catch (error) {
    console.error('Failed to save question:', error);
    $q.notify({ type: 'negative', message: (error as any).data?.error?.message || (error as any).data?.message || 'ไม่สามารถบันทึกคำถามได้', position: 'top' });
  } finally {
    savingQuestion.value = false;
  }
};

const addChoice = () => {
  questionForm.value.choices.push({ text: { th: '', en: '' }, is_correct: false });
};

const removeChoice = (index: number) => {
  const wasCorrect = questionForm.value.choices[index].is_correct;
  questionForm.value.choices.splice(index, 1);
  if (wasCorrect && questionForm.value.choices.length > 0) {
    questionForm.value.choices[0].is_correct = true;
  }
};

const getCorrectIndex = () => {
  return questionForm.value.choices.findIndex(c => c.is_correct);
};

const setCorrectChoice = (index: number) => {
  questionForm.value.choices.forEach((c, i) => {
    c.is_correct = i === index;
  });
};

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