<template>
  <BasicModal
    title="جزئیات تکلیف"
    title-en="Submission Details"
    width="95%"
    max-width="55rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div class="submission-details">
        <SkeletonLoaderBlock v-if="isLoading" :rows="3" :cols-per-row="1" />
        <template v-else-if="submission">
          <div class="submission-details__person">
            <div v-if="submission.user?.avatarUrl" class="submission-details__avatar">
              <img :src="submission.user.avatarUrl" :alt="userName" />
            </div>
            <div v-else class="submission-details__avatar submission-details__avatar--placeholder">
              <SvgIcon name="user" :size="32" color="#bcbcbc" />
            </div>
            <div class="submission-details__person-grid">
              <LineInfoBlock title="نام و نام خانوادگی" :desc="userName" />
              <LineInfoBlock
                title="وضعیت تحصیلی"
                :desc="EDUCATION_STATUS[submission.user?.profile?.educationStatus] || '—'"
              />
              <LineInfoBlock
                title="آخرین مدرک تحصیلی (طلبه)"
                :desc="SEMINARY_LEVEL[submission.user?.profile?.seminaryLevel] || '—'"
              />
              <LineInfoBlock
                title="آخرین مدرک تحصیلی"
                :desc="UNIVERSITY_LEVEL[submission.user?.profile?.universityLevel] || '—'"
              />
            </div>
          </div>

          <div class="submission-details__assignment">
            <p class="submission-details__assignment-title">{{ assignmentTitle }}</p>
            <div class="submission-details__assignment-meta">
              <span>ترم: {{ submission.termTitle || '—' }}</span>
              <span class="submission-details__sep">|</span>
              <span>دوره: {{ submission.courseTitle || '—' }}</span>
              <span class="submission-details__sep">|</span>
              <span>جلسه: {{ submission.sessionTitle || '—' }}</span>
              <span class="submission-details__sep">|</span>
              <span>تاریخ: {{ submittedAt }}</span>
            </div>
          </div>

          <div class="submission-details__row">
            <LineInfoBlock title="پاسخ طلبه" :desc="submission.userDescription || '—'" />
          </div>

          <div v-if="submission.attachments?.length" class="submission-details__attachments">
            <p class="submission-details__attachments-title">فایل‌های ارسالی</p>
            <ul>
              <li v-for="file in submission.attachments" :key="file.id">
                <a
                  :href="file.fileUrl || '#'"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="submission-details__file"
                >
                  <SvgIcon name="file" :size="16" color="var(--color-prim-gray)" />
                  <span>{{ file.title || `فایل ${file.id}` }}</span>
                </a>
              </li>
            </ul>
          </div>

          <form class="submission-details__review" @submit.prevent="onSubmit(close)">
            <div class="submission-details__review-grid">
              <TextField
                v-model="form.score"
                name="score"
                label="نمره"
                inputmode="numeric"
                :convert-digits="true"
                :error="errors.score"
                @blur="validateAt('score', form.score)"
              >
                <template #appendIcon>
                  <SvgIcon name="check" :size="18" color="var(--color-thd-gray)" />
                </template>
              </TextField>
              <SelectField
                v-model="form.status"
                name="status"
                label="وضعیت"
                :options="statusOptions"
                option-label="label"
                option-value="value"
                :error="errors.status"
              />
            </div>
            <TextareaField
              v-model="form.reviewerNote"
              name="reviewerNote"
              label="بازخورد"
              :row="4"
            />

            <div class="submission-details__divider" />

            <div class="submission-details__actions">
              <BaseButton
                variant="transparent"
                text="بستن"
                custom-class="submission-details__btn-cancel"
                @click="close"
              />
              <BaseButton
                type="submit"
                text="ثبت بازخورد"
                :loading="reviewMutation.isPending.value"
                custom-class="submission-details__btn-submit"
              >
                <template #appendIcon>
                  <SvgIcon name="arrow-left" :size="18" color="#fff" />
                </template>
              </BaseButton>
            </div>
          </form>
        </template>
        <NoItems v-else title="موردی یافت نشد" desc="جزئیات این تکلیف در دسترس نیست." />
      </div>
    </template>
  </BasicModal>
</template>

<script setup>
import useYup from '@/composables/useYup'
import { computed, ref, watch } from 'vue'
import useModal from '@/composables/useModal'
import { useQueryClient } from '@tanstack/vue-query'
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 TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import LineInfoBlock from '@/components/blocks/LineInfoBlock.vue'
import { EDUCATION_STATUS, SEMINARY_LEVEL, UNIVERSITY_LEVEL } from '@/enums'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import { assignmentSubmissionReviewSchema } from '@/features/admin/assignments/schema'
import {
  adminAssignmentsKeys,
  useAdminAssignmentSubmissionQuery,
  useReviewAdminAssignmentSubmissionMutation,
} from '@/services/query/admin-assignments'

defineOptions({ name: 'AssignmentSubmissionDetailsModal' })

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

const modalData = computed(() => getModal('AssignmentSubmissionDetailsModal')?.data ?? {})
const assignmentId = computed(() => modalData.value.assignmentId ?? null)
const submissionId = computed(() => modalData.value.submissionId ?? null)

const { data: fetched, isLoading } = useAdminAssignmentSubmissionQuery(assignmentId, submissionId, {
  enabled: () => !!assignmentId.value && !!submissionId.value,
})

const submission = computed(() => fetched.value || modalData.value.submission || null)

const userName = computed(() => {
  const u = submission.value?.user
  if (!u) return '—'
  return `${u.firstName || ''} ${u.lastName || ''}`.trim() || u.fullName || '—'
})

const assignmentTitle = computed(
  () => submission.value?.assignment?.title || modalData.value.assignmentTitle || '—'
)

const submittedAt = computed(
  () => submission.value?.faSubmittedAt || formatJalaaliDate(submission.value?.submittedAt) || '—'
)

const statusOptions = [
  { value: 'pending', label: 'در انتظار بررسی' },
  { value: 'approved', label: 'تایید شده' },
  { value: 'rejected', label: 'رد شده' },
  { value: 'needs_revision', label: 'نیازمند اصلاح' },
]

const schema = assignmentSubmissionReviewSchema

const { validate, validateAt, errors } = useYup(schema)

const form = ref({ score: '', status: 'approved', reviewerNote: '' })

watch(submission, (sub) => {
  if (!sub) return
  form.value = {
    score: sub.score ?? '',
    status: sub.status || 'approved',
    reviewerNote: sub.reviewerNote || '',
  }
})

const reviewMutation = useReviewAdminAssignmentSubmissionMutation()

const onSubmit = async (close) => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  await reviewMutation.mutateAsync({
    assignmentId: assignmentId.value,
    submissionId: submissionId.value,
    payload,
  })
  await queryClient.invalidateQueries({ queryKey: adminAssignmentsKeys.all })
  close()
}
</script>

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

  &__person {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin: 1rem 0 1.25rem;
  }

  &__avatar {
    width: 4.9rem;
    height: 4.9rem;
    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;
    }
  }

  &__person-grid {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.25rem;

    @media (min-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }
  }

  &__assignment {
    border-inline-end: 3px solid #ebebeb;
    padding-inline-end: 0.875rem;
    margin-block: 1rem;
  }

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

  &__assignment-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
    color: #535353;
  }

  &__sep {
    color: #d6d6d6;
  }

  &__row {
    margin-block: 0.5rem;
  }

  &__attachments {
    margin-block: 1rem;
  }

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

  &__file {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    color: var(--color-primary);
    text-decoration: none;
    font-family: var(--font-family-fa);
    font-size: 0.85rem;
    padding: 0.25rem 0;

    &:hover {
      text-decoration: underline;
    }
  }

  &__review {
    margin-top: 1.25rem;
  }

  &__review-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.5rem;

    @media (min-width: 640px) {
      grid-template-columns: repeat(2, 1fr);
    }
  }

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

  &__actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.625rem;
  }

  &__btn-cancel {
    min-width: 9rem;
  }

  &__btn-submit {
    min-width: 12rem;
  }
}
</style>
