<template>
  <div class="student-missionary">
    <BoxedIconTitleBlock
      class="student-missionary__heading"
      title="سامانه اعزام"
      desc="در این قسمت شما میتوانید درخواست های اعزام، تاریخچه اعزام و... را مشاهده کنید."
    >
      <template #icon>
        <SvgIcon name="paper-plane-right" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <MissionaryUserCard
      :profile="profile"
      @complete-info="onCompleteInfo"
      @settings="onProfileSettings"
      @add-narrative="onAddNarrative"
    />

    <TabsBlock v-model="activeTab" :tabs="tabs">
      <template #my-requests>
        <SkeletonLoaderBlock v-if="requestsLoading" :rows="3" :cols-per-row="1" />
        <div v-else-if="requests.length > 0">
          <MissionaryRequestItem
            v-for="request in requests"
            :key="request.id"
            :request="request"
            @show-details="onRequestDetails"
            @change-status="onAskChangeStatus"
          />
        </div>
        <NoItems v-else title="موردی نیست" desc="هنوز درخواستی ثبت نکرده‌اید." />
        <PaginationBlock :pagination="requestsMeta" @update:page="setRequestsPage" />
      </template>

      <template #history>
        <SkeletonLoaderBlock v-if="dispatchesLoading" :rows="3" :cols-per-row="1" />
        <div v-else-if="dispatches.length > 0">
          <MissionaryDispatchItem
            v-for="dispatch in dispatches"
            :key="dispatch.id"
            :dispatch="dispatch"
            @show-details="onDispatchDetails"
          />
        </div>
        <NoItems v-else title="موردی نیست" desc="تاریخچه اعزامی موجود نیست." />
        <PaginationBlock :pagination="dispatchesMeta" @update:page="setDispatchesPage" />
      </template>

      <template #narratives>
        <SkeletonLoaderBlock v-if="narrativesLoading" :rows="3" :cols-per-row="1" />
        <div v-else-if="narratives.length > 0">
          <MissionaryNarrativeItem
            v-for="narrative in narratives"
            :key="narrative.id"
            :narrative="narrative"
            @show-details="onNarrativeDetails"
            @edit="onEditNarrative"
            @delete="onAskDeleteNarrative"
          />
        </div>
        <NoItems v-else title="موردی نیست" desc="هنوز روایتی ثبت نکرده‌اید." />
        <PaginationBlock :pagination="narrativesMeta" @update:page="setNarrativesPage" />
      </template>
    </TabsBlock>

    <RequestDetailsModal v-if="isModal('RequestDetailsModal')" />
    <DispatchDetailsModal v-if="isModal('DispatchDetailsModal')" />
    <NarrativeDetailsModal v-if="isModal('NarrativeDetailsModal')" />
    <CreateNarrativeModal v-if="isModal('CreateNarrativeModal')" />
    <CompleteInfoModal v-if="isModal('MissionaryCompleteInfoModal')" />
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import useAuth from '@/composables/useAuth'
import useModal from '@/composables/useModal'
import { useRoute, useRouter } from 'vue-router'
import { MISSIONARY_REQUEST_STATUS } from '@/enums'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { useQueryClient } from '@tanstack/vue-query'
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 { formatJalaaliDate, formatJalaaliDateTime } from '@/utils/date-utils'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import MissionaryUserCard from '@/features/missionary/components/MissionaryUserCard.vue'
import MissionaryRequestItem from '@/features/missionary/components/MissionaryRequestItem.vue'
import MissionaryDispatchItem from '@/features/missionary/components/MissionaryDispatchItem.vue'
import RequestDetailsModal from '@/features/missionary/components/modals/RequestDetailsModal.vue'
import MissionaryNarrativeItem from '@/features/missionary/components/MissionaryNarrativeItem.vue'
import DispatchDetailsModal from '@/features/missionary/components/modals/DispatchDetailsModal.vue'
import CreateNarrativeModal from '@/features/missionary/components/modals/CreateNarrativeModal.vue'
import NarrativeDetailsModal from '@/features/missionary/components/modals/NarrativeDetailsModal.vue'
import CompleteInfoModal from '@/features/missionary/components/modals/completeInfo/CompleteInfoModal.vue'
import {
  missionaryMemoriesKeys,
  useDeleteMissionaryMemoryMutation,
  useMissionaryMemoriesListQuery,
} from '@/services/query/missionary-memories'
import {
  missionaryRequestsKeys,
  useChangeMissionaryRequestStatusMutation,
  useMissionaryRequestsListQuery,
} from '@/services/query/missionary-requests'

const { user } = useAuth()
const { openModal, isModal } = useModal()

const route = useRoute()
const router = useRouter()

const tabs = [
  { name: 'my-requests', label: 'درخواست های من', icon: 'list-bullets' },
  { name: 'history', label: 'تاریخچه اعزام ها', icon: 'paper-plane-right' },
  { name: 'narratives', label: 'روایت های من', icon: 'pencil' },
]

const isValidTab = (name) => tabs.some((tab) => tab.name === name)
const activeTab = ref(isValidTab(route.query.tab) ? route.query.tab : 'my-requests')

watch(activeTab, (tab) => {
  if (route.query.tab === tab) return
  router.replace({ query: { ...route.query, tab } }).catch(() => {})
})

const requestsFilters = ref({})
const dispatchesFilters = ref({ status: 'accepted' })
const narrativesFilters = ref({})

const { pagination: requestsPagination, setPage: setRequestsPage } = usePagination({
  page: 1,
  perPage: 10,
})
const { pagination: dispatchesPagination, setPage: setDispatchesPage } = usePagination({
  page: 1,
  perPage: 10,
})
const { pagination: narrativesPagination, setPage: setNarrativesPage } = usePagination({
  page: 1,
  perPage: 10,
})

const { data: requestsData, isLoading: requestsLoading } = useMissionaryRequestsListQuery(
  requestsFilters,
  requestsPagination,
  {
    enabled: () => activeTab.value === 'my-requests',
    keepPreviousData: true,
  }
)

const { data: dispatchesData, isLoading: dispatchesLoading } = useMissionaryRequestsListQuery(
  dispatchesFilters,
  dispatchesPagination,
  {
    enabled: () => activeTab.value === 'history',
    keepPreviousData: true,
  }
)

const { data: narrativesData, isLoading: narrativesLoading } = useMissionaryMemoriesListQuery(
  narrativesFilters,
  narrativesPagination,
  {
    enabled: () => activeTab.value === 'narratives',
    keepPreviousData: true,
  }
)

const requestStatusLabel = (status) => MISSIONARY_REQUEST_STATUS[status] || status || '—'

const toRequestView = (request) => ({
  ...request,
  code: request.id,
  requestNumber: request.id,
  requestDate: formatJalaaliDate(request.requestedDate),
  statusLabel: requestStatusLabel(request.status),
  phone: request.requesterPhone,
  address: request.location,
})

const toDispatchView = (request) => ({
  id: request.id,
  code: request.id,
  title: request.title,
  missionName: request.title,
  location: request.location,
  dispatchDate: formatJalaaliDate(request.requestedDate),
  statusLabel: requestStatusLabel(request.status),
  requesterName: request.requesterName,
  address: request.location,
  result: request.description,
})

const NARRATIVE_KIND_META = {
  manuscript: { label: 'دست نوشته', tone: 'pink' },
  dispatched: { label: 'اعزام شــــده', tone: 'gold' },
}

const toNarrativeView = (narrative) => {
  const linkedKind =
    narrative.missionaryRequestId || narrative.missionaryRequest ? 'dispatched' : 'manuscript'
  const kind = narrative.type || narrative.kind || linkedKind
  const kindMeta = NARRATIVE_KIND_META[kind] || NARRATIVE_KIND_META.manuscript
  return {
    ...narrative,
    code: narrative.id,
    submittedAt: formatJalaaliDateTime(narrative.createdAt),
    kind,
    kindLabel: kindMeta.label,
    kindTone: kindMeta.tone,
    body: narrative.description || narrative.content || narrative.body || '',
    likes: narrative.likesCount ?? narrative.likes ?? 0,
    comments: narrative.commentsCount ?? narrative.comments ?? 0,
  }
}

const requests = computed(() =>
  (requestsData.value?.data?.items ?? []).map((r) => toRequestView(r))
)
const dispatches = computed(() =>
  (dispatchesData.value?.data?.items ?? []).map((r) => toDispatchView(r))
)
const narratives = computed(() =>
  (narrativesData.value?.data?.items ?? []).map((n) => toNarrativeView(n))
)

const membershipDays = computed(() => {
  const created = new Date(user.value?.createdAt)
  if (Number.isNaN(created.getTime())) return '—'
  return Math.max(0, Math.floor((Date.now() - created.getTime()) / 86_400_000))
})

const profile = computed(() => ({
  fullName: user.value?.name || '—',
  city: user.value?.city?.name || '',
  avatar: user.value?.avatarUrl || '',
  phone: user.value?.phone || '',
  rating: user.value?.rating ?? '',
  membershipDays: membershipDays.value,
  requestsCount: requestsData.value?.meta?.total ?? '',
}))

const requestsMeta = computed(() => ({
  page: requestsPagination.value.page,
  perPage: requestsPagination.value.perPage,
  ...requestsData.value?.meta,
}))
const dispatchesMeta = computed(() => ({
  page: dispatchesPagination.value.page,
  perPage: dispatchesPagination.value.perPage,
  ...dispatchesData.value?.meta,
}))
const narrativesMeta = computed(() => ({
  page: narrativesPagination.value.page,
  perPage: narrativesPagination.value.perPage,
  ...narrativesData.value?.meta,
}))

const onCompleteInfo = () => {
  openModal('MissionaryCompleteInfoModal')
}

const onProfileSettings = () => {}

const queryClient = useQueryClient()
const statusMutation = useChangeMissionaryRequestStatusMutation()

const invalidateRequests = () =>
  queryClient.invalidateQueries({ queryKey: missionaryRequestsKeys.all, refetchType: 'all' })

const STATUS_CONFIRMS = {
  accepted: { title: 'پذیرش درخواست', verb: 'پذیرش' },
  rejected: { title: 'رد درخواست', verb: 'رد' },
}

const onAskChangeStatus = ({ id, status }) => {
  const config = STATUS_CONFIRMS[status]
  if (!config) return
  const request = requests.value.find((r) => r.id === id)
  openModal('ConfirmModal', {
    title: config.title,
    message: `آیا از ${config.verb} درخواست <strong>${request?.title || ''}</strong> مطمئن هستید؟`,
    onConfirm: () =>
      statusMutation.mutate({ id, payload: { status } }, { onSuccess: invalidateRequests }),
  })
}

const deleteMemoryMutation = useDeleteMissionaryMemoryMutation()

const invalidateMemories = () =>
  queryClient.invalidateQueries({ queryKey: missionaryMemoriesKeys.all, refetchType: 'all' })

const onAddNarrative = () => {
  openModal('CreateNarrativeModal')
}

const onEditNarrative = (narrative) => {
  openModal('CreateNarrativeModal', { memory: narrative })
}

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

const onRequestDetails = (request) => {
  openModal('RequestDetailsModal', request)
}

const onDispatchDetails = (dispatch) => {
  openModal('DispatchDetailsModal', dispatch)
}

const onNarrativeDetails = (narrative) => {
  openModal('NarrativeDetailsModal', narrative)
}
</script>

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

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