<template>
  <BasicModal
    title="شرکت‌کنندگان"
    title-en="Participants"
    width="95%"
    max-width="60rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ data, close }">
      <div class="exam-participants">
        <p v-if="data?.title" class="exam-participants__exam">{{ data.title }}</p>

        <SkeletonLoaderBlock v-if="isLoading" :rows="4" :cols-per-row="1" />
        <div v-else-if="attempts.length > 0" class="exam-participants__list">
          <div v-for="attempt in attempts" :key="attempt.id" class="exam-participants__row">
            <div class="exam-participants__user">
              <div v-if="avatarOf(attempt)" class="exam-participants__avatar">
                <img :src="avatarOf(attempt)" :alt="userName(attempt)" />
              </div>
              <div v-else class="exam-participants__avatar exam-participants__avatar--placeholder">
                <SvgIcon name="user" :size="20" color="#bcbcbc" />
              </div>
              <div>
                <p class="exam-participants__name">{{ userName(attempt) }}</p>
                <p class="exam-participants__location">{{ locationOf(attempt) || '—' }}</p>
              </div>
            </div>

            <div class="exam-participants__pill">
              <span class="exam-participants__pill-label">تاریخ شرکت:</span>
              <span class="exam-participants__pill-value">{{ submittedAt(attempt) }}</span>
            </div>

            <div
              class="exam-participants__score"
              :class="`exam-participants__score--${attempt.isPassed ? 'pass' : 'fail'}`"
            >
              <span class="exam-participants__score-label">نمره:</span>
              <span class="exam-participants__score-value">{{ attempt.score ?? '—' }}</span>
            </div>

            <BaseButton
              text="جزئیات"
              custom-class="exam-participants__details-btn"
              @click="onShowDetails(attempt)"
            >
              <template #appendIcon>
                <SvgIcon name="caret-left" :size="14" color="#fff" />
              </template>
            </BaseButton>
          </div>
        </div>
        <NoItems v-else title="موردی یافت نشد" desc="شرکت‌کننده‌ای ثبت نشده است." />

        <PaginationBlock :pagination="paginationMeta" @update:page="setPage" />

        <div class="exam-participants__divider" />

        <div class="exam-participants__footer">
          <BaseButton text="بستن" custom-class="exam-participants__close-btn" @click="close">
            <template #appendIcon>
              <SvgIcon name="arrow-left" :size="18" color="#fff" />
            </template>
          </BaseButton>
        </div>
      </div>
    </template>
  </BasicModal>
</template>

<script setup>
import { computed, ref } 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 { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import { useAdminExamAttemptsQuery } from '@/services/query/admin-exams'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'

defineOptions({ name: 'ExamParticipantsModal' })

const { getModal, openModal } = useModal()

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

const filters = ref({})
const { pagination, setPage } = usePagination({ page: 1, perPage: 10 })

const { data, isLoading } = useAdminExamAttemptsQuery(examId, filters, pagination, {
  enabled: () => !!examId.value,
  keepPreviousData: true,
})

const attempts = computed(() => data.value?.data ?? [])
const paginationMeta = computed(() => ({
  page: pagination.value.page,
  perPage: pagination.value.perPage,
  ...data.value?.meta,
}))

const userOf = (attempt) => attempt?.user ?? {}

const userName = (attempt) => {
  const u = userOf(attempt)
  return u.name || `${u.firstName || ''} ${u.lastName || ''}`.trim() || '—'
}

const avatarOf = (attempt) => {
  const u = userOf(attempt)
  return u.avatarDownloadUrl || u.avatarUrl || ''
}

const locationOf = (attempt) => {
  const u = userOf(attempt)
  const province = u.province?.name || ''
  const city = u.city?.name || ''
  return [province, city].filter(Boolean).join('، ')
}

const submittedAt = (attempt) =>
  attempt.faSubmittedAt || formatJalaaliDate(attempt.submittedAt) || '—'

const onShowDetails = (attempt) => {
  const u = userOf(attempt)
  openModal('ExamParticipantDetailsModal', {
    examId: examId.value,
    attemptId: attempt.id,
    participantId: u.id,
    participant: {
      id: u.id,
      firstName: u.firstName ?? u.name ?? '',
      lastName: u.lastName ?? '',
      fullName: u.name ?? '',
      avatarUrl: avatarOf(attempt),
    },
    attempt,
  })
}
</script>

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

  &__exam {
    font-family: var(--font-family-fa);
    font-size: 0.85rem;
    color: var(--color-prim-gray);
    margin: 0 0 0.75rem;
  }

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

  &__row {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    padding: 0.625rem 0.875rem;
    background: rgba(255, 255, 255, 60%);
    border-radius: 0.875rem;
    box-shadow: 0 4px 10px -6px rgba(241, 241, 241, 70%);
    flex-wrap: wrap;
  }

  &__user {
    flex: 1 1 40%;
    display: flex;
    align-items: center;
    gap: 0.625rem;
    min-width: 0;
  }

  &__avatar {
    width: 2.75rem;
    height: 2.75rem;
    border-radius: 9999px;
    overflow: hidden;
    background: #f5f5f5;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    &--placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

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

  &__location {
    font-family: var(--font-family-fa);
    font-size: 0.7rem;
    color: #989898;
    margin: 0;
  }

  &__pill {
    background: rgba(107, 107, 107, 5%);
    border-radius: 0.875rem;
    padding: 0.375rem 1rem;
    text-align: center;
    min-width: 9rem;
    white-space: nowrap;
  }

  &__pill-label {
    font-family: var(--font-family-fa);
    font-size: 0.7rem;
    color: #535353;
    margin-inline-end: 0.25rem;
  }

  &__pill-value {
    font-family: var(--font-family-en);
    font-size: 0.7rem;
    color: #535353;
  }

  &__score {
    border-radius: 0.875rem;
    padding: 0.375rem 1rem;
    text-align: center;
    min-width: 6rem;
    white-space: nowrap;

    &--pass {
      background: rgba(46, 160, 67, 10%);
      color: #2ea043;
    }

    &--fail {
      background: rgba(229, 72, 77, 10%);
      color: #e5484d;
    }
  }

  &__score-label {
    font-family: var(--font-family-fa);
    font-size: 0.7rem;
    margin-inline-end: 0.25rem;
  }

  &__score-value {
    font-family: var(--font-family-en);
    font-size: 0.8rem;
    font-weight: 600;
  }

  &__details-btn {
    min-width: 5rem;
    padding: 0 1rem;
  }

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

  &__footer {
    display: flex;
    justify-content: flex-end;
  }

  &__close-btn {
    min-width: 12rem;
  }
}
</style>
