<template>
  <BasicModal
    title="اطلاعات شخصی"
    title-en="Personal information"
    width="95%"
    max-width="80rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default>
      <div v-if="detailsLoading || !user" class="user-verification-details">
        <p class="user-verification-details__loading">در حال بارگذاری…</p>
      </div>
      <div v-else ref="pdfContent" class="user-verification-details">
        <header class="user-verification-details__pdf-header">
          <h1>اطلاعات احراز هویت کاربر</h1>
          <p>{{ fullName }}</p>
        </header>

        <section class="user-verification-details__section">
          <div class="user-verification-details__grid user-verification-details__grid--6">
            <LineInfoBlock title="نام و نام خانوادگی" :numeric-desc="fullName" />
            <LineInfoBlock
              title="تاریخ تولد"
              :numeric-desc="formatJalaaliDate(personal.birthDate) || ''"
            />
            <LineInfoBlock title="شماره تماس" :numeric-desc="personal.phone" />
            <LineInfoBlock title="کد ملی" :numeric-desc="personal.nationalCode" />
            <LineInfoBlock title="وضعیت" :desc="MARITAL_STATUS[personal.maritalStatus] || ''" />
            <LineInfoBlock title="جنسیت" :desc="GENDER[personal.gender] || ''" />
            <LineInfoBlock title="استان" :desc="personal.province || '-'" />
            <LineInfoBlock title="شهر" :desc="personal.city || '-'" />
            <div class="user-verification-details__cell user-verification-details__cell--span-3">
              <LineInfoBlock title="آدرس" :desc="personal.address || '-'" />
            </div>
          </div>
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="اطلاعات تحصیلی" title-en="Academic information" />
          <div class="user-verification-details__grid user-verification-details__grid--4">
            <LineInfoBlock
              title="وضعیت تحصیلی"
              :desc="EDUCATION_STATUS[profile.educationStatus] || ''"
            />
            <LineInfoBlock
              title="آخرین مدرک تحصیلی (طلبه)"
              :desc="SEMINARY_LEVEL[profile.seminaryLevel] || ''"
            />
            <LineInfoBlock
              title="آخرین مدرک تحصیلی"
              :desc="UNIVERSITY_LEVEL[profile.universityLevel] || ''"
            />
            <LineInfoBlock title="نام حوزه علمیه/دانشگاه" :desc="profile.universityName || ''" />
            <div class="user-verification-details__cell user-verification-details__cell--full">
              <LineInfoBlock
                title="گرایش تخصصی حوزوی / رشته تحصیلی دانشگاهی"
                :desc="profile.fieldOfStudy || ''"
              />
            </div>
          </div>
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="اطلاعات شغلی" title-en="Job information" />
          <div class="user-verification-details__grid user-verification-details__grid--4">
            <div class="user-verification-details__cell user-verification-details__cell--full">
              <LineInfoBlock
                title="خلاصه‌ای از فعالیت‌ها در موقعیت‌های شغلی"
                :desc="profile.activitySummary || ''"
              />
            </div>
          </div>
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock
            title="اطلاعات فعالیت تبلیغاتی و حرفه‌ای"
            title-en="Advertising and professional activity information"
          />
          <LineInfoBlock
            title="سابقه فعالیت تبلیغی شما چند سال می‌باشد؟"
            :numeric-desc="profile.propagationExperienceYears ?? ''"
          />
          <LineInfoBlock
            title="توضیحات مدل فعالیت تبلیغی"
            :desc="profile.propagationMethodDescription || ''"
          />
          <LineInfoBlock title="موضوعات تخصصی تبلیغی" :desc="profile.specializedTopics || ''" />
          <LineInfoBlock title="بسترهای فعالیت تبلیغی" :desc="platformsLabel" />
          <LineInfoBlock
            v-if="otherPlatformDetails"
            title="توضیح فعالیت در سایر فضاهای تبلیغی"
            :desc="otherPlatformDetails"
          />
          <LineInfoBlock
            v-if="onlinePlatformDetails"
            title="نام شبکه و مدل فعالیت تبلیغی"
            :desc="onlinePlatformDetails"
          />
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="مهارت‌ها و تخصص‌ها (1)" title-en="Skills and Specialties" />
          <LineInfoBlock
            title="عملکرد در شرایط رضایت پایین مخاطبین"
            :desc="LOW_SATISFACTION_RESPONSE[profile.responseToLowSatisfaction] || ''"
          />
          <LineInfoBlock
            v-if="profile.responseToLowSatisfactionDescription"
            title="توضیح گزینه «سایر»"
            :desc="profile.responseToLowSatisfactionDescription"
          />
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="مهارت‌ها و تخصص‌ها (2)" title-en="Skills and Specialties" />
          <LineInfoBlock
            title="مواجهه با تعطیلی جلسه به دلیل هزینه"
            :desc="SESSION_CANCELLATION_RESPONSE[profile.responseToSessionCancellation] || ''"
          />
          <LineInfoBlock
            v-if="profile.responseToSessionCancellationDescription"
            title="توضیح گزینه «سایر»"
            :desc="profile.responseToSessionCancellationDescription"
          />
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="مهارت‌ها و تخصص‌ها (3)" title-en="Skills and Specialties" />
          <LineInfoBlock
            title="مواجهه با تناقض درخواست مخاطبین"
            :desc="AUDIENCE_CONFLICT_RESPONSE[profile.responseToAudienceConflict] || ''"
          />
          <LineInfoBlock
            v-if="profile.responseToAudienceConflictDescription"
            title="توضیح گزینه «سایر»"
            :desc="profile.responseToAudienceConflictDescription"
          />
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="مهارت‌ها و تخصص‌ها (4)" title-en="Skills and Specialties" />
          <LineInfoBlock
            title="مواجهه با مبلغه رقیب"
            :desc="COMPETING_PROPAGATOR_RESPONSE[profile.responseToCompetingPropagator] || ''"
          />
          <LineInfoBlock
            v-if="profile.responseToCompetingPropagatorDescription"
            title="توضیح گزینه «سایر»"
            :desc="profile.responseToCompetingPropagatorDescription"
          />
        </section>

        <section class="user-verification-details__section">
          <LineTitleBlock title="مهارت‌ها و تخصص‌ها (5)" title-en="Skills and Specialties" />
          <LineInfoBlock
            title="مواجهه با مدعیان نسخه‌های دینی"
            :desc="profile.responseToUnqualifiedAdvisors || ''"
          />
          <LineInfoBlock
            title="مدارک و گواهینامه‌های مرتبط"
            :desc="profile.relevantCertificates || ''"
          />
          <LineInfoBlock title="مواجهه با موضوع حجاب" :desc="profile.hijabApproach || ''" />
        </section>

        <section v-if="faithProduction?.url" class="user-verification-details__section">
          <LineTitleBlock title="بخش صوت" title-en="Audio section" />
          <LineInfoBlock title="نظر و تحلیل از ویدئو ارائه شده" />
          <div class="user-verification-details__voice">
            <VoiceRecorder :model-value="faithProduction" disabled />
          </div>
        </section>

        <section v-if="leaderMessage?.url" class="user-verification-details__section">
          <LineTitleBlock title="بخش تصویر" title-en="Video section" />
          <LineInfoBlock title="درک و برداشت از پیام رهبری" />
          <video
            :src="leaderMessage.url"
            controls
            playsinline
            class="user-verification-details__video"
          />
        </section>

        <div class="user-verification-details__divider" />

        <div class="user-verification-details__actions" data-pdf-ignore>
          <BaseButton
            text="ذخیره به صورت PDF"
            :loading="pdfLoading"
            custom-class="user-verification-details__pdf-btn"
            @click="onSaveAsPdf"
          >
            <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 { toast } from 'vue3-toastify'
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 { formatJalaaliDate } from '@/utils/date-utils'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import VoiceRecorder from '@/components/form/VoiceRecorder.vue'
import LineInfoBlock from '@/components/blocks/LineInfoBlock.vue'
import { useAdminUserQuery, useAdminUserRegisterDataQuery } from '@/services/query/admin-users'
import {
  AUDIENCE_CONFLICT_RESPONSE,
  COMPETING_PROPAGATOR_RESPONSE,
  EDUCATION_STATUS,
  GENDER,
  LOW_SATISFACTION_RESPONSE,
  MARITAL_STATUS,
  PROPAGATION_PLATFORM,
  SEMINARY_LEVEL,
  SESSION_CANCELLATION_RESPONSE,
  UNIVERSITY_LEVEL,
} from '@/enums'

defineOptions({ name: 'UserVerificationDetailsModal' })

const { getModal } = useModal()

const modalData = computed(() => getModal('UserVerificationDetailsModal')?.data ?? {})
const userId = computed(() => modalData.value.id ?? null)
const userIdRef = computed(() => userId.value)

const { data: fetched, isLoading: userLoading } = useAdminUserQuery(userIdRef, {
  enabled: () => !!userIdRef.value,
})

const { data: registerData, isLoading: registerDataLoading } = useAdminUserRegisterDataQuery(
  userIdRef,
  {
    enabled: () => !!userIdRef.value,
  }
)

const user = computed(() => modalData.value.user || fetched.value || null)
const detailsLoading = computed(() => userLoading.value || registerDataLoading.value)

const profile = computed(() => ({ ...user.value?.profile, ...registerData.value }))

const fullName = computed(() => user.value?.name || '—')
const personal = computed(() => {
  const u = user.value || {}
  const p = u.profile || {}
  return {
    birthDate: u.birthday || p.birthDate || '',
    phone: u.phone || u.phoneNumber || '',
    nationalCode: u.nationalCode || '',
    maritalStatus: u.marriageStatus || p.maritalStatus || '',
    gender: u.gender || p.gender || '',
    address: typeof u.address === 'string' ? u.address : u.address?.address || '',
    province: u.province?.name || u.address?.province?.name || '',
    city: u.city?.name || u.address?.city?.name || '',
  }
})

const platforms = computed(() =>
  Array.isArray(profile.value.propagationPlatforms) ? profile.value.propagationPlatforms : []
)

const platformsLabel = computed(() =>
  platforms.value
    .map((p) => PROPAGATION_PLATFORM[p.platform] || p.platform)
    .filter(Boolean)
    .join(' ، ')
)

const otherPlatformDetails = computed(
  () => platforms.value.find((p) => p.platform === 'other')?.platformDetails || ''
)
const onlinePlatformDetails = computed(
  () => platforms.value.find((p) => p.platform === 'online')?.platformDetails || ''
)

// Skill parts 6 & 7 store the uploaded media objects in register-data under
// `faithProductionAudio` / `leaderMessageVideo` (each carries a `url`).
const faithProduction = computed(() => profile.value.faithProductionAudio || null)
const leaderMessage = computed(() => profile.value.leaderMessageVideo || null)

const pdfContent = ref(null)
const pdfLoading = ref(false)

const onSaveAsPdf = async () => {
  if (!pdfContent.value || !userId.value || detailsLoading.value || pdfLoading.value) return

  pdfLoading.value = true
  try {
    await document.fonts?.ready

    const pdfSource = pdfContent.value.cloneNode(true)
    pdfSource.classList.add('user-verification-details--pdf')
    pdfSource.querySelectorAll('[data-pdf-ignore]').forEach((element) => element.remove())

    const html2pdfModule = await import('html2pdf.js')
    const html2pdf = html2pdfModule.default || html2pdfModule

    await html2pdf()
      .set({
        margin: [8, 8, 8, 8],
        filename: `user-verification-${userId.value}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: {
          scale: 2,
          useCORS: true,
          backgroundColor: '#ffffff',
          logging: false,
        },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        pagebreak: {
          mode: ['css', 'legacy'],
          avoid: ['.user-verification-details__section'],
        },
      })
      .from(pdfSource)
      .save()
  } catch {
    toast.error('ساخت فایل PDF با خطا مواجه شد.')
  } finally {
    pdfLoading.value = false
  }
}
</script>

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

  &__pdf-header {
    display: none;
  }

  &__loading {
    text-align: center;
    padding: 2rem;
    color: var(--color-prim-gray);
  }

  &__section {
    margin-bottom: 1.5rem;
  }

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

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

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

  &__cell {
    &--span-2 {
      @media (min-width: 768px) {
        grid-column: span 2;
      }
    }

    &--span-3 {
      @media (min-width: 768px) {
        grid-column: span 3;
      }
    }

    &--full {
      grid-column: 1 / -1;
    }
  }

  &__person {
    display: flex;
    align-items: center;
    gap: 0.625rem;
  }

  &__avatar {
    height: 6rem;
    width: 6rem;
    min-width: 6rem;
    border-radius: 9999px;
    border: 1px solid #eee;
    overflow: hidden;

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

    &--placeholder {
      background: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      border: none;
    }
  }

  &__person-info {
    text-align: start;
  }

  &__person-label {
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
    color: #b7b7b7;
    margin: 0;
  }

  &__person-name {
    font-family: var(--font-family-fa);
    font-weight: 500;
    font-size: 0.875rem;
    color: #4b4b4b;
    margin: 0.25rem 0;
  }

  &__status-badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    border-radius: 0.375rem;
    font-size: 0.75rem;
    margin: 0;

    &--pending {
      background: rgba(0, 255, 68, 6%);
    }

    &--rejected {
      background: rgba(204, 40, 49, 6%);
    }
  }

  &__status-label {
    color: #808080;
    padding-inline: 0.125rem;
  }

  &__status-value {
    font-family: var(--font-family-fa);
    font-weight: 500;
    font-size: 0.875rem;
    padding-inline: 0.125rem;

    /* stylelint-disable-next-line selector-class-pattern */
    .user-verification-details__status-badge--pending & {
      color: #009a12;
    }

    /* stylelint-disable-next-line selector-class-pattern */
    .user-verification-details__status-badge--rejected & {
      color: var(--color-primary);
    }
  }

  &__audio,
  &__video {
    width: 100%;
    margin-top: 0.5rem;
  }

  &__voice {
    margin-top: 0.5rem;

    /* stylelint-disable-next-line selector-class-pattern */
    :deep(.voice-recorder) {
      min-height: auto;
      padding: 0.75rem;
    }

    /* stylelint-disable-next-line selector-class-pattern */
    :deep(.voice-recorder__main-btn) {
      width: 4rem;
      height: 4rem;
    }
  }

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

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

  &__pdf-btn {
    min-width: 12rem;
  }

  &--pdf {
    width: 100%;
    padding: 0.25rem;
    background: #fff;
    box-sizing: border-box;
    direction: rtl;
  }

  &--pdf &__pdf-header {
    display: block;
    margin-bottom: 1.5rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid #eee;
    text-align: right;
    break-after: avoid;

    h1 {
      margin: 0;
      font-family: var(--font-family-fa);
      font-size: 1.25rem;
      font-weight: 500;
      color: #4b4b4b;
    }

    p {
      margin: 0.25rem 0 0;
      font-family: var(--font-family-fa);
      font-size: 0.875rem;
      color: #808080;
    }
  }

  &--pdf &__section {
    margin-bottom: 1rem;
    break-inside: avoid;
    page-break-inside: avoid;
  }

  &--pdf &__grid--4 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  &--pdf &__grid--6 {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  &--pdf &__cell--span-3 {
    grid-column: span 3;
  }

  &--pdf :deep(.line-info__title) {
    overflow: visible;
    text-overflow: initial;
    white-space: normal;
  }
}
</style>
