<script setup lang="ts">
/**
 * @file my-courses.vue
 * @description My Courses Page.
 * Displays enrolled courses with filters for progress/completed.
 * Handles enrollment success modals and certificate downloads.
 */

definePageMeta({
  layout: 'default',
  middleware: 'auth'
})

useHead({
  title: 'คอร์สของฉัน - e-Learning'
})

const route = useRoute()
const showEnrollModal = ref(false)
const activeFilter = ref<'all' | 'progress' | 'completed'>('all')


// Check URL query parameters to show 'Enrollment Success' modal
onMounted(() => {
  if (route.query.enrolled) {
    showEnrollModal.value = true
  }
})

// Helper to get localized text
const getLocalizedText = (text: string | { th: string; en: string } | undefined) => {
  if (!text) return ''
  if (typeof text === 'string') return text
  return text.th || text.en || ''
}

// Data Handling
const { fetchEnrolledCourses, getCertificate, generateCertificate } = useCourse()
const enrolledCourses = ref<any[]>([])
const isLoading = ref(false)
const isDownloadingCert = ref(false)

const loadEnrolledCourses = async () => {
  isLoading.value = true
  // FIX: For 'progress' tab, we want both ENROLLED and IN_PROGRESS.
  // Since API takes single status, we fetch ALL and filter locally for 'progress'.
  const apiStatus = activeFilter.value === 'completed' 
      ? 'COMPLETED' 
      : undefined // 'all' or 'progress' -> fetch all

  const res = await fetchEnrolledCourses({ 
    status: apiStatus
  })

  if (res.success) {
    let courses = (res.data || [])

    // Local filter for 'progress' tab to exclude completed
    if (activeFilter.value === 'progress') {
        courses = courses.filter(c => c.status !== 'COMPLETED')
    }

    enrolledCourses.value = courses.map(item => ({
      id: item.course_id, 
      enrollment_id: item.id,
      title: getLocalizedText(item.course.title),
      progress: item.progress_percentage || 0, 
      completed: item.status === 'COMPLETED',
      thumbnail_url: item.course.thumbnail_url 
    }))
  }
  isLoading.value = false
}

// Watch filter changes to reload
watch(activeFilter, () => {
  loadEnrolledCourses()
})

onMounted(() => {
  if (route.query.enrolled) {
    showEnrollModal.value = true
  }
  loadEnrolledCourses()
})

// Certificate Handling
const downloadingCourseId = ref<number | null>(null)
// Certificate Handling

const downloadCertificate = async (course: any) => {
  if (!course) return
  downloadingCourseId.value = course.id
  
  try {
      // 1. Try to GET existing certificate
      let res = await getCertificate(course.id)

      // 2. If not found (or error), try to GENERATE new one
      if (!res.success) {
         res = await generateCertificate(course.id)
      }

      // 3. Handle Result
      if (res.success && res.data) {
          const cert = res.data
          if (cert.download_url) {
              window.open(cert.download_url, '_blank')
          } else {
              // Fallback if no URL but success (maybe show message)
              console.warn('Certificate ready but no URL')
          }
      } else {
           // Silent fail or minimal log, or maybe use a toast if available, but avoid $q if undefined
           console.error(res.error || 'Failed to get certificate')
      }
  } catch (e) {
      console.error(e)
  } finally {
      downloadingCourseId.value = null
  }
}

const validCourseId = computed(() => {
    const cid = route.query.course_id
    if (!cid || cid === 'undefined' || cid === 'null' || cid === 'NaN') return null
    return cid
})
</script>

<template>
  <div class="p-8 max-w-6xl mx-auto">


    <!-- Page Header & Filters -->
    <div class="flex flex-col items-start mb-12">
       <h1 class="text-3xl font-extrabold text-slate-900 dark:text-white mb-8">{{ $t('sidebar.myCourses') }}</h1>

       <!-- Filter Tabs -->
       <div class="flex gap-2">
         <q-btn
           v-for="filter in ['all', 'progress', 'completed']"
           :key="filter"
           @click="activeFilter = filter as any"
           rounded
           unelevated
           :color="activeFilter === filter ? 'primary' : 'white'"
           :text-color="activeFilter === filter ? 'white' : 'grey-8'"
           class="font-bold px-6"
           :label="$t(`myCourses.filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`)"
         />
       </div>
    </div>

    <!-- Courses Grid -->
    <div v-if="isLoading" class="flex justify-center py-20">
       <q-spinner size="3rem" color="primary" />
    </div>
    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      <template v-for="course in enrolledCourses" :key="course.id">
        <!-- In Progress Course Card -->
        <CourseCard 
          v-if="!course.completed"
          :id="course.id"
          :title="course.title"
          :progress="course.progress"
          :image="course.thumbnail_url"
          show-continue
        />
        <!-- Completed Course Card -->
        <CourseCard 
          v-else
          :id="course.id"
          :title="course.title"
          :progress="100"
          :image="course.thumbnail_url"
          :completed="true"
          show-certificate
          show-study-again
          :loading="downloadingCourseId === course.id"
          @view-certificate="downloadCertificate(course)"
        />
      </template>
    </div>

    <!-- Empty State -->
    <div v-if="!isLoading && enrolledCourses.length === 0" class="flex flex-col items-center justify-center py-20 bg-slate-50 dark:bg-slate-800/50 rounded-3xl border-2 border-dashed border-slate-200 dark:border-slate-700 mt-4">
      <h3 class="text-xl font-bold text-slate-900 dark:text-white mb-2">{{ $t('myCourses.emptyTitle') }}</h3>
      <p class="text-slate-500 dark:text-slate-400 text-center max-w-md">{{ $t('myCourses.emptyDesc') }}</p>
      <NuxtLink to="/browse/discovery" class="mt-6 px-6 py-2 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-colors">{{ $t('myCourses.goToDiscovery') }}</NuxtLink>
    </div>

    <!-- MODAL: Enrollment Success -->
    <q-dialog v-model="showEnrollModal" backdrop-filter="blur(4px)">
      <q-card class="rounded-[1.5rem] shadow-2xl p-8 max-w-sm w-full text-center relative overflow-hidden bg-white dark:bg-slate-800">
        <div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-green-400 to-emerald-600"></div>
        <div class="w-16 h-16 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 rounded-full flex items-center justify-center text-3xl mx-auto mb-6">
          ✓
        </div>
        <h2 class="text-2xl font-bold mb-2 text-slate-900 dark:text-white">{{ $t('enrollment.successTitle') }}</h2>
        <p class="text-slate-500 dark:text-slate-400 mb-8">{{ $t('enrollment.successDesc') }}</p>
        <div class="flex flex-col gap-3">
          <q-btn
            v-if="validCourseId"
            :to="`/classroom/learning?course_id=${validCourseId}`"
            unelevated
            rounded
            color="primary"
            class="w-full py-3 text-lg font-bold shadow-lg"
            :label="$t('enrollment.startNow')"
          />
           <q-btn
            v-else
            unelevated
            rounded
            color="primary"
            class="w-full py-3 text-lg font-bold shadow-lg"
            :label="$t('common.close')" 
            @click="showEnrollModal = false"
          />
          <q-btn
            v-if="validCourseId"
            flat
            rounded
            color="grey-7"
            class="w-full py-3 font-bold"
            :label="$t('enrollment.later')"
            @click="showEnrollModal = false"
          />
        </div>
      </q-card>
    </q-dialog>


  </div>
</template>

<style scoped>
/* Custom Font for Signature/Name if desired */
.font-handwriting {
  font-family: 'Dancing Script', cursive, serif; /* Fallback */
}
</style>
