<template>
  <BasicModal
    title="جزئیات تیکت"
    title-en="Ticket details"
    width="95%"
    max-width="58rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default>
      <div class="ticket-details">
        <div v-if="ticket" class="ticket-details__date">
          <span>{{ ticketDate }}</span>
        </div>

        <SkeletonLoaderBlock v-if="isLoading && !ticket" :rows="3" :cols-per-row="1" />
        <div
          v-else-if="messages.length > 0 || ticketMedia.length > 0"
          ref="thread"
          class="ticket-details__thread"
        >
          <div v-if="ticketMedia.length > 0" class="ticket-details__row ticket-details__row--self">
            <div class="ticket-details__bubble">
              <MessageAttachments :media="ticketMedia" />
              <span class="ticket-details__time">{{ messageTime(ticket) }}</span>
            </div>
          </div>
          <div
            v-for="message in messages"
            :key="message.id"
            class="ticket-details__row"
            :class="`ticket-details__row--${senderClass(message)}`"
          >
            <div class="ticket-details__bubble">
              <MessageAttachments v-if="message.media?.length" :media="message.media" />
              <p class="ticket-details__text">{{ message.message }}</p>
              <span class="ticket-details__time">{{ messageTime(message) }}</span>
            </div>
          </div>
        </div>
        <NoItems v-else title="پیامی نیست" desc="هنوز پیامی در این تیکت ثبت نشده است." />

        <div class="ticket-details__divider" />

        <form class="ticket-details__compose" @submit.prevent="onSend">
          <button
            type="submit"
            :disabled="!canSend"
            class="ticket-details__send"
            aria-label="ارسال"
          >
            <SvgIcon name="paper-plane-right" :size="22" color="var(--color-primary)" />
          </button>
          <input
            v-model="text"
            type="text"
            placeholder="ارسال پیام"
            class="ticket-details__input"
          />
        </form>
      </div>
    </template>
  </BasicModal>
</template>

<script setup>
import useModal from '@/composables/useModal'
import { computed, nextTick, ref, watch } from 'vue'
import { useQueryClient } from '@tanstack/vue-query'
import BasicModal from '@/components/BasicModal.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { formatJalaaliDate } from '@/utils/date-utils'
import MessageAttachments from '@/components/blocks/MessageAttachments.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import {
  studentTicketsKeys,
  useSendStudentTicketMessageMutation,
  useStudentTicketQuery,
} from '@/services/query/student-tickets'

defineOptions({ name: 'TicketDetailsModal' })

const queryClient = useQueryClient()
const { getModal } = useModal()

const modalData = computed(() => getModal('TicketDetailsModal')?.data ?? {})
const ticketId = computed(() => modalData.value.id ?? null)

const { data: ticket, isLoading } = useStudentTicketQuery(ticketId, {
  enabled: () => !!ticketId.value,
})

const messages = computed(() => ticket.value?.messages ?? [])

const ticketMedia = computed(() => ticket.value?.media ?? [])

const ticketDate = computed(() => formatJalaaliDate(ticket.value?.createdAt) || '—')

// Student viewing their own ticket — their own messages get the highlighted
// (primary-color) `self` bubble; admin/counselor replies get the muted `other`
// bubble. The viewer's id matches the ticket's studentId here.
const senderClass = (message) => (message.senderId === ticket.value?.studentId ? 'self' : 'other')

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

const text = ref('')
const canSend = computed(() => text.value.trim().length > 0)

const sendMutation = useSendStudentTicketMessageMutation()

const onSend = async () => {
  if (!canSend.value || !ticketId.value) return
  const value = text.value.trim()
  text.value = ''
  // Backend POST /student/tickets/:id/messages — body is { message: string }.
  await sendMutation.mutateAsync({ id: ticketId.value, payload: { message: value } })
  await queryClient.invalidateQueries({ queryKey: studentTicketsKeys.all })
}

const thread = ref(null)

watch(messages, async () => {
  await nextTick()
  if (thread.value) {
    thread.value.scrollTop = thread.value.scrollHeight
  }
})
</script>

<style lang="scss" scoped>
.ticket-details {
  width: 100%;
  text-align: start;
  display: flex;
  flex-direction: column;
  max-height: calc(100dvh - 8rem);
  min-height: 28rem;

  &__date {
    display: flex;
    justify-content: center;
    margin: 0.5rem 0 0.875rem;
  }

  &__date span {
    background: #f7f7f7;
    color: #9c9c9c;
    border-radius: 9999px;
    padding: 0.5rem 1.25rem;
    font-family: var(--font-family-en);
    font-size: 0.75rem;
  }

  &__thread {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    padding-block: 0.5rem 1rem;
    padding-inline-end: 0.25rem;
  }

  &__row {
    display: flex;

    // `self` (the viewer / student) sits on the visual end (left in RTL) with
    // the highlighted primary bubble. `other` sits at the start (right in
    // RTL) with the muted gray bubble.
    &--self {
      justify-content: flex-end;
    }

    &--other {
      justify-content: flex-start;
    }
  }

  &__bubble {
    max-width: 72%;
    border-radius: 1rem;
    padding: 0.75rem 1.25rem;

    .ticket-details__row--self & {
      background: var(--color-primary);
      color: #fff;
      border-end-end-radius: 0;
    }

    .ticket-details__row--other & {
      background: #f8f8f8;
      color: #5d5d5d;
      border-end-start-radius: 0;
    }
  }

  &__text {
    font-family: var(--font-family-fa);
    font-size: 0.875rem;
    line-height: 1.7;
    margin: 0;
  }

  &__time {
    display: block;
    margin-top: 0.375rem;
    font-family: var(--font-family-en);
    font-size: 0.7rem;

    .ticket-details__row--self & {
      color: rgba(255, 255, 255, 80%);
    }

    .ticket-details__row--other & {
      color: #b1b1b1;
    }
  }

  &__divider {
    border-block-end: 1px solid var(--color-thd-gray);
    margin-block: 0.75rem;
  }

  &__compose {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  &__send {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 9999px;
    border: none;
    background: transparent;
    color: var(--color-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.2s ease;

    &:hover:enabled {
      background: var(--color-primary);
      color: #fff;
    }

    &:disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }

  &__input {
    flex: 1;
    height: 2.5rem;
    border: 1px solid transparent;
    border-radius: 1.5rem;
    padding: 0 1rem;
    font-family: var(--font-family-fa);
    font-size: 0.875rem;
    color: #4b4b4b;
    outline: none;

    &:focus {
      border-color: var(--color-thd-gray);
    }
  }
}
</style>
