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

    <SessionsFilters v-model="filters" @apply="onFilterApply" @reset="onFilterReset" />

    <div class="sessions-page__list-header">
      <SimpleTitleIconBlock title="لیست همه جلسات" class="sessions-page__list-title">
        <template #header-icon>
          <SvgIcon name="list-bullets" :size="16" color="#bcbcbc" />
        </template>
      </SimpleTitleIconBlock>
      <BaseButton text="افزودن جلسه جدید" custom-class="sessions-page__add-btn" @click="onAdd">
        <template #appendIcon>
          <SvgIcon name="arrow-left" :size="18" color="#fff" />
        </template>
      </BaseButton>
    </div>

    <SkeletonLoaderBlock v-if="isLoading" :rows="6" :cols-per-row="1" />
    <div v-else-if="sessions.length > 0">
      <SessionItem
        v-for="session in sessions"
        :key="session.id"
        :session="session"
        @edit="onEdit"
        @delete="onAskDelete"
        @show-details="onShowDetails"
        @show-attendance="onShowAttendance"
      />
    </div>
    <NoItems v-else title="متاسفیم" desc="جلسه‌ای برای نمایش وجود ندارد." />

    <PaginationBlock :pagination="paginationMeta" @update:page="setPage" />

    <SessionAttendanceModal v-if="isModal('SessionAttendanceModal')" />
    <SessionDetailsModal v-if="isModal('SessionDetailsModal')" />
  </div>
</template>

<script setup>
import useModal from '@/composables/useModal'
import { useRoute, useRouter } from 'vue-router'
import { useQueryClient } from '@tanstack/vue-query'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { computed, onMounted, ref, watch } from 'vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import SessionItem from '@/features/admin/sessions/components/SessionItem.vue'
import SimpleTitleIconBlock from '@/components/blocks/SimpleTitleIconBlock.vue'
import SessionsFilters from '@/features/admin/sessions/components/SessionsFilters.vue'
import SessionDetailsModal from '@/features/admin/sessions/components/modals/SessionDetailsModal.vue'
import SessionAttendanceModal from '@/features/admin/sessions/components/modals/SessionAttendanceModal.vue'
import {
  adminSessionsKeys,
  useAdminSessionsListQuery,
  useDeleteAdminSessionMutation,
} from '@/services/query/admin-sessions'

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

const routeCourseId = computed(() => (route.params.courseId ? Number(route.params.courseId) : null))

const filters = ref({
  title: '',
  courseId: routeCourseId.value ?? '',
  sessionType: '',
  fromDate: '',
  toDate: '',
})
const { pagination, setPage, reset: resetPagination } = usePagination({ page: 1, perPage: 10 })

const syncRouteCourseId = (courseId) => {
  if (!courseId) return
  filters.value = { ...filters.value, courseId }
  resetPagination()
}

onMounted(() => syncRouteCourseId(routeCourseId.value))
watch(routeCourseId, (val) => syncRouteCourseId(val))

const { data, isLoading } = useAdminSessionsListQuery(filters, pagination, {
  keepPreviousData: true,
})

const sessions = computed(() => data.value?.data ?? [])
const paginationMeta = computed(() => ({
  page: pagination.value.page,
  perPage: pagination.value.perPage,
  ...data.value?.meta,
}))

const onFilterApply = () => resetPagination()
const onFilterReset = () => resetPagination()

const onAdd = () => {
  router
    .push({
      name: 'admin-add-session',
      query: routeCourseId.value ? { courseId: routeCourseId.value } : undefined,
    })
    .catch(() => {})
}

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

const onShowDetails = (session) => {
  openModal('SessionDetailsModal', { id: session.id })
}

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

const deleteMutation = useDeleteAdminSessionMutation()

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

const onShowAttendance = (session) => {
  openModal('SessionAttendanceModal', { id: session.id, title: session.title })
}
</script>

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

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__list-header {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    margin-bottom: 0.375rem;
  }

  &__list-title {
    flex: 1;
    margin-bottom: 0;
  }

  &__add-btn {
    min-width: fit-content;
    padding: 0 1.25rem;
  }
}
</style>
