<template>
  <BasicModal
    title="جزئیات مشاوره"
    title-en="Consultation Details"
    width="95%"
    max-width="64rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default>
      <div class="consultation-details">
        <div v-if="consultation" class="consultation-details__date">
          <span>{{ consultationDate }}</span>
        </div>

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

        <div class="consultation-details__divider" />

        <form class="consultation-details__compose" @submit.prevent="onSend">
          <button
            type="submit"
            :disabled="!canSend"
            class="consultation-details__send"
            aria-label="ارسال"
          >
            <SvgIcon name="paper-plane-right" :size="22" color="var(--color-primary)" />
          </button>
          <input
            v-model="text"
            type="text"
            placeholder="ارسال پیام"
            class="consultation-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 SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import {
  adminConsultationsKeys,
  useAdminConsultationQuery,
  useSendAdminConsultationMessageMutation,
} from '@/services/query/admin-consultations'

defineOptions({ name: 'ConsultationDetailsModal' })

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

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

const { data: consultation, isLoading } = useAdminConsultationQuery(consultationId, {
  enabled: () => !!consultationId.value,
})

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

const consultationDate = computed(() => formatJalaaliDate(consultation.value?.createdAt) || '—')

// Student is "the user"; everyone else (counselor, admin) renders on the
// opposite side of the thread. Same rule as the admin tickets modal.
const senderClass = (message) =>
  message.senderId === consultation.value?.studentId ? 'user' : 'admin'

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 = useSendAdminConsultationMessageMutation()

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

const thread = ref(null)

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

<style lang="scss" scoped>
.consultation-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;

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

    &--user {
      justify-content: flex-end;
    }
  }

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

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

    .consultation-details__row--user & {
      background: #f8f8f8;
      color: #5d5d5d;
      border-end-end-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;

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

    .consultation-details__row--user & {
      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>
