<template>
  <div class="student-certificates">
    <BoxedIconTitleBlock
      class="student-certificates__heading"
      title="گواهینامه های شما"
      desc="در این قسمت شما میتوانید گواهینامه هر دوره ای را که گذرانده اید را مشاهده کنید."
    >
      <template #icon>
        <SvgIcon name="certificate" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <SimpleTitleIconBlock title="گواهینامه های شما" class="student-certificates__section-title">
      <template #header-icon>
        <SvgIcon name="list-bullets" :size="16" color="#bcbcbc" />
      </template>
    </SimpleTitleIconBlock>

    <SkeletonLoaderBlock v-if="isLoading" :rows="3" :cols-per-row="1" />
    <div v-else-if="certificates.length > 0">
      <CertificateItem
        v-for="certificate in certificates"
        :key="certificate.id"
        :certificate="certificate"
        @download="onDownload"
      />
    </div>
    <NoItems v-else title="موردی نیست" desc="هنوز گواهینامه‌ای ندارید." />
    <PaginationBlock :pagination="meta" @update:page="setPage" />
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { toast } from 'vue3-toastify'
import SvgIcon from '@/components/icons/SvgIcon.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 SimpleTitleIconBlock from '@/components/blocks/SimpleTitleIconBlock.vue'
import CertificateItem from '@/features/student/certificates/components/CertificateItem.vue'
import {
  useDownloadStudentCertificateMutation,
  useStudentCertificatesQuery,
} from '@/services/query/student-certificates'

const filters = ref({})
const { pagination, setPage } = usePagination({ page: 1, perPage: 10 })

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

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

const downloadMutation = useDownloadStudentCertificateMutation()

const onDownload = async ({ certificate, format }) => {
  try {
    const response = await downloadMutation.mutateAsync({ id: certificate.id, format })
    const url = response?.data?.url
    if (url && url !== '#') {
      window.open(url, '_blank')
    } else {
      toast.info('فایل گواهینامه در دسترس نیست.')
    }
  } catch {
    toast.error('دانلود گواهینامه با خطا مواجه شد.')
  }
}
</script>

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

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__section-title {
    margin-block: 0.25rem;
  }
}
</style>
