<template>
  <div class="terms-page">
    <BoxedIconTitleBlock
      class="terms-page__heading"
      title="مدیریت ترم"
      desc="در این قسمت می‌توانید ترم‌های خود را مدیریت کنید"
    >
      <template #icon>
        <SvgIcon name="book" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

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

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

    <SkeletonLoaderBlock v-if="isLoading" :rows="6" :cols-per-row="1" />
    <div v-else-if="terms.length > 0">
      <TermItem
        v-for="term in terms"
        :key="term.id"
        :term="term"
        @edit="onEdit"
        @delete="onAskDelete"
        @clone="onClone"
        @change-status="onChangeStatus"
        @show-details="onShowDetails"
      />
    </div>
    <NoItems v-else title="متاسفیم" desc="ترمی برای نمایش وجود ندارد." />

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

    <TermDetailsModal v-if="isModal('TermDetailsModal')" />
    <AddTermStudentModal v-if="isModal('AddTermStudentModal')" />
    <AttachCourseToTermModal v-if="isModal('AttachCourseToTermModal')" />
    <AddOfferedCourseModal v-if="isModal('AddOfferedCourseModal')" />
    <CourseDetailsModal v-if="isModal('CourseDetailsModal')" />
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import useModal from '@/composables/useModal'
import { useQueryClient } from '@tanstack/vue-query'
import BaseButton from '@/components/BaseButton.vue'
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 TermItem from '@/features/admin/terms/components/TermItem.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import TermsFilters from '@/features/admin/terms/components/TermsFilters.vue'
import SimpleTitleIconBlock from '@/components/blocks/SimpleTitleIconBlock.vue'
import { CourseDetailsModal, AddOfferedCourseModal } from '@/features/admin/courses'
import TermDetailsModal from '@/features/admin/terms/components/modals/TermDetailsModal.vue'
import AddTermStudentModal from '@/features/admin/terms/components/modals/AddTermStudentModal.vue'
import AttachCourseToTermModal from '@/features/admin/terms/components/modals/AttachCourseToTermModal.vue'
import {
  adminTermsKeys,
  useAdminTermsListQuery,
  useDeleteAdminTermMutation,
  useUpdateAdminTermMutation,
} from '@/services/query/admin-terms'

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

const filters = ref({ title: '', status: '', fromDate: '', toDate: '' })
const { pagination, setPage, reset: resetPagination } = usePagination({ page: 1, perPage: 10 })

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

const terms = 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-term' }).catch(() => {})
}

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

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

const deleteMutation = useDeleteAdminTermMutation()
// Backend has no dedicated status endpoint — PATCH /terms/:id with { isActive }.
const updateMutation = useUpdateAdminTermMutation()

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

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

const onShowDetails = (term) => {
  openModal('TermDetailsModal', { id: term.id })
}
</script>

<style lang="scss" scoped>
.terms-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>
