<template>
  <div class="student-services">
    <BoxedIconTitleBlock
      class="student-services__heading"
      title="خدمات"
      desc="درخواست خدمت ثبت کنید یا تاریخچه درخواست‌های خود را مشاهده نمایید."
    >
      <template #icon>
        <SvgIcon name="paper-plane" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <TabsBlock v-model="activeTab" :tabs="tabs">
      <template #create>
        <CreateServiceForm
          :submitting="createMutation.isPending.value"
          @submit="onSubmit"
          @file-error="onFileError"
        />
      </template>

      <template #history>
        <SkeletonLoaderBlock v-if="historyLoading" :rows="3" :cols-per-row="1" />
        <div v-else-if="services.length > 0">
          <ServiceItem
            v-for="service in services"
            :key="service.id"
            :service="service"
            @show-details="onShowDetails"
          />
        </div>
        <NoItems v-else title="موردی نیست" desc="هنوز درخواستی ثبت نکرده‌اید." />
        <PaginationBlock :pagination="historyMeta" @update:page="setHistoryPage" />
      </template>
    </TabsBlock>

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

<script setup>
import { computed, ref } from 'vue'
import { toast } from 'vue3-toastify'
import { TICKET_STATUS } from '@/enums'
import useModal from '@/composables/useModal'
import { useQueryClient } from '@tanstack/vue-query'
import SvgIcon from '@/components/icons/SvgIcon.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 BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import ServiceItem from '@/features/student/services/components/ServiceItem.vue'
import CreateServiceForm from '@/features/student/services/components/CreateServiceForm.vue'
import ServiceDetailsModal from '@/features/student/services/components/modals/ServiceDetailsModal.vue'
import {
  studentTicketsKeys,
  useCreateStudentTicketMutation,
  useStudentTicketsQuery,
} from '@/services/query/student-tickets'

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

const tabs = [
  { name: 'create', label: 'درخواست خدمت', icon: 'paper-plane' },
  { name: 'history', label: 'تاریخچه درخواست ها', icon: 'list-bullets' },
]
const activeTab = ref('create')

const historyFilters = ref({ type: 'service' })
const { pagination: historyPagination, setPage: setHistoryPage } = usePagination({
  page: 1,
  perPage: 10,
})

const { data: historyData, isLoading: historyLoading } = useStudentTicketsQuery(
  historyFilters,
  historyPagination,
  {
    enabled: () => activeTab.value === 'history',
    keepPreviousData: true,
  }
)

// ServiceItem expects title/requestNumber/typeLabel/statusLabel. Bridge the
// new backend payload (subject/id/category/status) without changing the item
// template.
const services = computed(() =>
  (historyData.value?.data?.items ?? []).map((t) => ({
    ...t,
    title: t.subject ?? '',
    requestNumber: t.id,
    typeLabel: t.category ?? '',
    statusLabel: TICKET_STATUS[t.status] ?? '',
  }))
)
const historyMeta = computed(() => ({
  page: historyPagination.value.page,
  perPage: historyPagination.value.perPage,
  ...historyData.value?.meta,
}))

const createMutation = useCreateStudentTicketMutation()

const onSubmit = async (formPayload) => {
  try {
    await createMutation.mutateAsync({
      type: 'service',
      category: formPayload.category,
      subject: formPayload.subject,
      message: formPayload.message,
      mediaIds: formPayload.mediaIds,
    })
    toast.success('درخواست خدمت با موفقیت ثبت شد.')
    await queryClient.invalidateQueries({ queryKey: studentTicketsKeys.all })
    activeTab.value = 'history'
  } catch {
    toast.error('ثبت درخواست با خطا مواجه شد.')
  }
}

const onFileError = (msg) => toast.warning(msg)

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

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

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