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

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

    <SimpleTitleIconBlock title="لیست تمام خدمات خواسته شده" class="services-page__list-title">
      <template #header-icon>
        <SvgIcon name="list-bullets" :size="16" color="#bcbcbc" />
      </template>
    </SimpleTitleIconBlock>

    <SkeletonLoaderBlock v-if="isLoading" :rows="6" :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"
        @change-status="onChangeStatus"
      />
    </div>
    <NoItems v-else title="متاسفیم" desc="درخواست خدمتی برای نمایش وجود ندارد." />

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

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

<script setup>
import { computed, ref } from 'vue'
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 { 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/admin/services/components/ServiceItem.vue'
import SimpleTitleIconBlock from '@/components/blocks/SimpleTitleIconBlock.vue'
import ServicesFilters from '@/features/admin/services/components/ServicesFilters.vue'
import SendMessageModal from '@/features/admin/services/components/modals/SendMessageModal.vue'
import ServiceDetailsModal from '@/features/admin/services/components/modals/ServiceDetailsModal.vue'
import {
  adminServicesKeys,
  useAdminServicesListQuery,
  useChangeAdminServiceStatusMutation,
} from '@/services/query/admin-services'

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

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

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

// Backend payload doesn't include the UI's legacy fields (requestId, faCreatedAt,
// user.firstName/lastName, typeLabel/statusLabel). Bridge them here so ServiceItem
// and the modals can stay untouched.
const services = computed(() =>
  (data.value?.data?.items ?? []).map((s) => ({
    ...s,
    requestId: s.requestId ?? s.id,
    user:
      s.user ??
      (s.student
        ? {
            id: s.student.id,
            firstName: s.student.name?.split(' ')[0] || '',
            lastName: s.student.name?.split(' ').slice(1).join(' ') || '',
            fullName: s.student.name,
            avatarUrl: s.student.avatarUrl,
          }
        : null),
  }))
)

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

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

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

const changeStatusMutation = useChangeAdminServiceStatusMutation()

const onChangeStatus = async ({ service, status }) => {
  await changeStatusMutation.mutateAsync({ id: service.id, payload: { status } })
  await queryClient.invalidateQueries({ queryKey: adminServicesKeys.all })
}
</script>

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

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__list-title {
    margin-bottom: 0.375rem;
  }
}
</style>
