<template>
  <div class="student-consultants">
    <BoxedIconTitleBlock
      class="student-consultants__heading"
      title="مشاوره"
      desc="درخواست مشاوره جدید ثبت کنید یا تاریخچه مشاوره‌های خود را مشاهده نمایید."
    >
      <template #icon>
        <img :src="chatsImage" alt="مشاوره" class="student-consultants__heading-img" />
      </template>
    </BoxedIconTitleBlock>

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

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

<script setup>
import { computed, ref } from 'vue'
import { toast } from 'vue3-toastify'
import { TICKET_STATUS } from '@/enums'
import { useQueryClient } from '@tanstack/vue-query'
import NoItems from '@/components/blocks/NoItems.vue'
import { formatJalaaliDate } from '@/utils/date-utils'
import TabsBlock from '@/components/blocks/TabsBlock.vue'
import chatsImage from '@/assets/images/tickets/chats.png'
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 ConsultantItem from '@/features/student/consultants/components/ConsultantItem.vue'
import RequestConsultantForm from '@/features/student/consultants/components/RequestConsultantForm.vue'
import {
  studentTicketsKeys,
  useCreateStudentTicketMutation,
  useStudentTicketsQuery,
} from '@/services/query/student-tickets'

const queryClient = useQueryClient()

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

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

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

const formatTime = (iso) => {
  if (!iso) return ''
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return ''
  return d.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' })
}

// ConsultantItem expects title/requestNumber/dateLabel/timeLabel/statusLabel.
// Bridge the new backend payload without touching the item template.
const consultants = computed(() =>
  (historyData.value?.data?.items ?? []).map((t) => ({
    ...t,
    title: t.subject ?? '',
    requestNumber: t.id,
    dateLabel: formatJalaaliDate(t.createdAt) || '',
    timeLabel: formatTime(t.createdAt),
    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: 'advise',
      subject: formPayload.subject,
      message: formPayload.message,
    })
    toast.success('درخواست مشاوره با موفقیت ثبت شد.')
    await queryClient.invalidateQueries({ queryKey: studentTicketsKeys.all })
    activeTab.value = 'history'
  } catch {
    toast.error('ثبت درخواست با خطا مواجه شد.')
  }
}

const onShowDetails = () => {}
</script>

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

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__heading-img {
    width: 1.75rem;
    height: 1.75rem;
    object-fit: contain;
  }
}
</style>
