<template>
  <BasicModal
    title="شرکت کنندگان"
    title-en="Participants"
    width="95%"
    max-width="76rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div class="participant-details">
        <p v-if="participantName" class="participant-details__name">{{ participantName }}</p>

        <div class="participant-details__card">
          <SkeletonLoaderBlock v-if="isLoading" :rows="3" :cols-per-row="1" />
          <div v-else-if="attempts.length > 0" class="participant-details__list">
            <div v-for="attempt in attempts" :key="attempt.id" class="participant-details__attempt">
              <button
                type="button"
                class="participant-details__attempt-head"
                @click="toggle(attempt.id)"
              >
                <div class="participant-details__caret">
                  <SvgIcon
                    :name="isOpen(attempt.id) ? 'caret-down' : 'caret-left'"
                    :size="24"
                    color="#d8d8d8"
                  />
                </div>
                <div class="participant-details__attempt-info">
                  <p class="participant-details__attempt-title">{{ attempt.title }}</p>
                  <div class="participant-details__attempt-meta">
                    <div class="participant-details__meta-item">
                      <span class="participant-details__meta-label">دوره :</span>
                      <span class="participant-details__meta-value">{{ attempt.courseTitle }}</span>
                    </div>
                    <div class="participant-details__meta-item">
                      <span class="participant-details__meta-label">جلسه :</span>
                      <span class="participant-details__meta-value">
                        {{ attempt.sessionTitle }}
                      </span>
                    </div>
                    <div class="participant-details__meta-item">
                      <span class="participant-details__meta-label">تاریخ :</span>
                      <span
                        class="participant-details__meta-value participant-details__meta-value--en"
                      >
                        {{ attempt.faDate }}
                      </span>
                    </div>
                    <div
                      class="participant-details__score"
                      :class="`participant-details__score--${attempt.tone}`"
                    >
                      <span class="participant-details__meta-label">نمره :</span>
                      <span class="participant-details__score-value">{{ attempt.score }}</span>
                    </div>
                  </div>
                </div>
              </button>

              <div v-if="isOpen(attempt.id)" class="participant-details__body">
                <div
                  v-for="(question, qIdx) in attempt.questions"
                  :key="question.id"
                  class="participant-details__question"
                >
                  <p class="participant-details__question-title">
                    {{ qIdx + 1 }}- {{ question.title }}
                  </p>
                  <div class="participant-details__answers">
                    <div
                      v-for="answer in question.answers"
                      :key="answer.id"
                      class="participant-details__answer"
                    >
                      <span
                        class="participant-details__answer-dot"
                        :class="answerStateClass(answer.id, question)"
                      />
                      <p class="participant-details__answer-text">{{ answer.title }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <NoItems v-else title="موردی یافت نشد" desc="تلاشی برای این شرکت‌کننده ثبت نشده است." />

          <div class="participant-details__divider" />
          <div class="participant-details__footer">
            <BaseButton text="تایید" custom-class="participant-details__confirm-btn" @click="close">
              <template #appendIcon>
                <SvgIcon name="arrow-left" :size="18" color="#fff" />
              </template>
            </BaseButton>
          </div>
        </div>
      </div>
    </template>
  </BasicModal>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import useModal from '@/composables/useModal'
import BasicModal from '@/components/BasicModal.vue'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { formatJalaaliDate } from '@/utils/date-utils'
import { useAdminExamAttemptQuery } from '@/services/query/admin-exams'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'

defineOptions({ name: 'ExamParticipantDetailsModal' })

const TONE_MAP = {
  good: 'success',
  success: 'success',
  bad: 'danger',
  danger: 'danger',
  neutral: 'neutral',
}

const { getModal } = useModal()

const modalData = computed(() => getModal('ExamParticipantDetailsModal')?.data ?? {})
const attemptId = computed(() => modalData.value.attemptId ?? null)
const participant = computed(() => modalData.value.participant ?? null)

const { data: detail, isLoading } = useAdminExamAttemptQuery(attemptId, {
  enabled: () => !!attemptId.value,
})

// The review endpoint returns one attempt; the template renders an accordion
// list, so wrap it as a single-element list (falling back to any attempts that
// were passed through on the modal data).
const rawAttempts = computed(() =>
  detail.value ? [detail.value] : participant.value?.attempts || []
)

const attempts = computed(() =>
  rawAttempts.value.map((attempt, index) => ({
    id: attempt.id ?? index + 1,
    title: attempt.title || `آزمون مرتبه ${index + 1}`,
    courseTitle: attempt.courseTitle || '—',
    sessionTitle: attempt.sessionTitle || '—',
    faDate: attempt.faDate || formatJalaaliDate(attempt.date) || '—',
    score: attempt.score ?? '—',
    tone: TONE_MAP[attempt.scoreTone] || 'neutral',
    questions: attempt.questions || [],
  }))
)

const participantName = computed(() => {
  const p = participant.value
  if (!p) return ''
  return `${p.firstName || ''} ${p.lastName || ''}`.trim() || p.fullName || ''
})

const openId = ref(null)
const isOpen = (id) => openId.value === id
const toggle = (id) => {
  openId.value = openId.value === id ? null : id
}

watch(
  attempts,
  (list) => {
    if (openId.value == null && list.length > 0) openId.value = list[0].id
  },
  { immediate: true }
)

const answerStateClass = (answerId, question) => {
  const isSelected = String(question.userAnswerId ?? question.selectedAnswerId) === String(answerId)
  const isCorrect = String(question.correctAnswerId) === String(answerId)
  if (isSelected && isCorrect) return 'participant-details__answer-dot--selected-correct'
  if (isCorrect) return 'participant-details__answer-dot--correct'
  if (isSelected) return 'participant-details__answer-dot--wrong'
  return ''
}
</script>

<style lang="scss" scoped>
.participant-details {
  width: 100%;
  text-align: start;

  &__name {
    font-family: var(--font-family-fa);
    font-size: 0.95rem;
    color: #4b4b4b;
    margin: 0.5rem 0 1rem;
  }

  &__card {
    border: 1px solid #e7e2dd;
    border-radius: 1.75rem;
    background: #fff;
    padding: 1rem;

    @media (min-width: 640px) {
      padding: 1.5rem;
    }
  }

  &__list {
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
  }

  &__attempt {
    border: 1px solid #e7e2dd;
    border-radius: 1.75rem;
    overflow: hidden;
    background: #fff;
  }

  &__attempt-head {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    width: 100%;
    padding: 1rem 1.25rem;
    border: none;
    background: transparent;
    cursor: pointer;
    text-align: start;

    @media (min-width: 640px) {
      padding: 1.25rem 1.5rem;
    }
  }

  &__caret {
    width: 2rem;
    height: 2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-top: 0.25rem;
  }

  &__attempt-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  }

  &__attempt-title {
    font-family: var(--font-family-fa);
    font-weight: 500;
    font-size: 1.125rem;
    line-height: 1.7;
    color: #494949;
    margin: 0;
  }

  &__attempt-meta {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem 1.25rem;
    color: #8e8e8e;
  }

  &__meta-item {
    white-space: nowrap;
    font-size: 0.875rem;
    line-height: 1.5;
  }

  &__meta-label {
    font-family: var(--font-family-fa);
    font-weight: 300;
    margin-inline-end: 0.25rem;
  }

  &__meta-value {
    font-family: var(--font-family-fa);
    color: #7c7c7c;
  }

  &__meta-value--en {
    font-family: var(--font-family-en);
  }

  &__score {
    padding: 0.375rem 0.75rem;
    border-radius: 0.55rem;
    font-family: var(--font-family-fa);
    font-size: 0.875rem;
    line-height: 1.3;

    &--success {
      background: #e8f8ee;
      color: #169c56;
    }

    &--danger {
      background: #fdebeb;
      color: #cc2831;
    }

    &--neutral {
      background: #f4f4f4;
      color: #8e8e8e;
    }
  }

  &__score-value {
    font-family: var(--font-family-en);
    font-weight: 500;
  }

  &__body {
    padding: 1.25rem;
    display: flex;
    flex-direction: column;
    gap: 2rem;

    @media (min-width: 640px) {
      padding: 1.25rem 1.5rem 1.5rem;
    }
  }

  &__question-title {
    font-family: var(--font-family-fa);
    font-weight: 300;
    font-size: 0.875rem;
    line-height: 1.75;
    color: #bdbdbd;
    margin: 0 0 1.25rem;
  }

  &__answers {
    display: flex;
    flex-wrap: wrap;
    gap: 1.25rem 3rem;
  }

  &__answer {
    display: inline-flex;
    align-items: baseline;
    gap: 0.375rem;
  }

  &__answer-dot {
    display: inline-block;
    width: 0.75rem;
    height: 0.75rem;
    border-radius: 0.25rem;
    border: 1px solid #d4d4d4;
    background: transparent;
    flex-shrink: 0;

    &--correct {
      border-color: #007074;
      background: #007074;
    }

    &--wrong {
      border-color: #cc2831;
      background: #cc2831;
    }

    &--selected-correct {
      border-color: #9a9a9a;
      background: #9a9a9a;
    }
  }

  &__answer-text {
    font-family: var(--font-family-fa);
    font-size: 1rem;
    line-height: 1.7;
    color: #5b5b5b;
    margin: 0;
  }

  &__divider {
    border-block-end: 1px solid #e7e2dd;
    margin-block: 1.5rem 1rem;
  }

  &__footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 0.75rem;
  }

  &__confirm-btn {
    min-width: 11.5rem;
    padding: 0 2rem;
  }
}
</style>
