<template>
  <div class="courses-page">
    <BoxedIconTitleBlock
      class="courses-page__heading"
      title="مدیریت دوره"
      desc="در این قسمت می‌توانید دوره‌های خود را مدیریت کنید"
    >
      <template #icon>
        <img :src="courseIcon" alt="" />
      </template>
    </BoxedIconTitleBlock>

    <CoursesFilters v-model="offeredFilters" @apply="onFilterApply" @reset="onFilterReset" />

    <TabsBlock :tabs="tabs">
      <template #offered>
        <SkeletonLoaderBlock v-if="offeredPending" :rows="6" :cols-per-row="1" />
        <div v-else-if="offered.length > 0">
          <CourseItem
            v-for="course in offered"
            :key="course.id"
            :course="course"
            @edit="onEditCourse"
            @delete="onAskDelete"
            @change-status="onChangeStatus"
            @show-details="onShowDetails"
          />
        </div>
        <NoItems v-else title="متاسفیم" desc="دوره‌ای برای نمایش وجود ندارد." />
        <PaginationBlock :pagination="offeredPaginationMeta" @update:page="setOfferedPage" />
      </template>
    </TabsBlock>

    <CourseDetailsModal v-if="isModal('CourseDetailsModal')" />
    <AddSessionToCourseModal v-if="isModal('AddSessionToCourseModal')" />
  </div>
</template>

<script setup>
import { gallery } from '@/utils/gallery'
import useModal from '@/composables/useModal'
import { useRoute, useRouter } from 'vue-router'
import { useQueryClient } from '@tanstack/vue-query'
import { computed, onMounted, ref, watch } from 'vue'
import NoItems from '@/components/blocks/NoItems.vue'
import TabsBlock from '@/components/blocks/TabsBlock.vue'
import { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import CourseItem from '@/features/admin/courses/components/CourseItem.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import CoursesFilters from '@/features/admin/courses/components/CoursesFilters.vue'
import CourseDetailsModal from '@/features/admin/courses/components/modals/CourseDetailsModal.vue'
import AddSessionToCourseModal from '@/features/admin/courses/components/modals/AddSessionToCourseModal.vue'
import {
  adminCoursesKeys,
  useAdminCoursesListQuery,
  useDeleteAdminCourseMutation,
  useUpdateAdminCourseMutation,
} from '@/services/query/admin-courses'

const route = useRoute()
const router = useRouter()
const queryClient = useQueryClient()
const { openModal, isModal } = useModal()

const courseIcon = gallery.courseIcon

const routeTermId = computed(() => (route.params.termId ? Number(route.params.termId) : null))

const onAdd = () => {
  router
    .push({
      name: 'admin-add-course',
      query: routeTermId.value ? { termId: routeTermId.value } : undefined,
    })
    .catch(() => {})
}

const tabs = [
  {
    name: 'offered',
    label: 'دوره‌های ارائه شده',
    icon: 'list-bullets',
    hasButton: true,
    textButton: 'افزودن دوره ارائه شده جدید',
    buttonAction: onAdd,
  },
]

const offeredFilters = ref({})

const {
  pagination: offeredPagination,
  setPage: setOfferedPage,
  reset: resetOfferedPagination,
} = usePagination({ page: 1, perPage: 10 })

const { data: offeredData, isLoading: offeredPending } = useAdminCoursesListQuery(
  offeredFilters,
  offeredPagination,
  { keepPreviousData: true }
)

const offered = computed(() => offeredData.value?.data ?? [])
const offeredPaginationMeta = computed(() => ({
  page: offeredPagination.value.page,
  perPage: offeredPagination.value.perPage,
  ...offeredData.value?.meta,
}))

const onFilterApply = () => resetOfferedPagination()
const onFilterReset = onFilterApply

const onEditCourse = (course) => {
  router.push({ name: 'admin-edit-course', params: { id: course.id } }).catch(() => {})
}

const onShowDetails = (course) => {
  openModal('CourseDetailsModal', { id: course.id })
}

const invalidate = () => queryClient.invalidateQueries({ queryKey: adminCoursesKeys.all })

const deleteMutation = useDeleteAdminCourseMutation()
const updateMutation = useUpdateAdminCourseMutation()

const onAskDelete = (course) => {
  openModal('ConfirmModal', {
    title: `حذف ${course.title}`,
    message: `بعد از حذف امکان بازگشت وجود ندارد، آیا مطمئن هستید که می‌خواهید <strong>${course.title}</strong> را حذف کنید؟`,
    onConfirm: () => deleteMutation.mutate(course.id, { onSuccess: invalidate }),
  })
}

const onChangeStatus = ({ id, isActive }) => {
  updateMutation.mutate({ id, payload: { isActive } }, { onSuccess: invalidate })
}

const syncRouteTermId = (termId) => {
  if (!termId) return
  offeredFilters.value = { ...offeredFilters.value, termId }
  resetOfferedPagination()
}

onMounted(() => syncRouteTermId(routeTermId.value))
watch(routeTermId, (val) => syncRouteTermId(val))
</script>

<style lang="scss" scoped>
.courses-page {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;

  &__heading {
    margin-bottom: 0.75rem;
  }
}
</style>
