<template>
  <BasicModal
    title="بخش معرفی"
    title-en="Introduction"
    width="95%"
    max-width="64rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div class="complete-info">
        <TextareaField
          v-model="store.introduction"
          name="introduction"
          label="لطفا خودتان را به صورت کامل معرفی نمایید."
          :row="5"
        />

        <section class="complete-info__section">
          <div class="complete-info__section-head">
            <LineTitleBlock title="مهارت های شما" title-en="Your Skills" />
            <BaseButton
              text="افزودن مهارت"
              custom-class="complete-info__add-btn"
              @click="openModal('MissionaryAddSkillModal')"
            >
              <template #appendIcon>
                <SvgIcon name="caret-left" :size="14" color="#fff" />
              </template>
            </BaseButton>
          </div>
          <div v-if="store.skills.length > 0" class="complete-info__badges">
            <Badge
              v-for="skill in store.skills"
              :key="skill.title"
              variant="neutral"
              :label="skill.title"
              :value="SKILL_LEVELS[skill.level] || skill.level"
            />
          </div>
        </section>

        <section class="complete-info__section">
          <div class="complete-info__section-head">
            <LineTitleBlock title="سوابق کاری" title-en="Work Experience" />
            <BaseButton
              text="افـــــــــــزودن"
              custom-class="complete-info__add-btn"
              @click="openModal('MissionaryAddWorkExperienceModal')"
            >
              <template #appendIcon>
                <SvgIcon name="caret-left" :size="14" color="#fff" />
              </template>
            </BaseButton>
          </div>
          <div v-if="store.workExperiences.length > 0" class="complete-info__entries">
            <EntryCard
              v-for="(item, index) in store.workExperiences"
              :key="index"
              :title="item.jobTitle"
              :subtitle="rangeSubtitle(item.organizationName, item.startYear, item.endYear)"
              @edit="openModal('MissionaryAddWorkExperienceModal', { entry: item, index })"
            />
          </div>
        </section>

        <section class="complete-info__section">
          <div class="complete-info__section-head">
            <LineTitleBlock title="سوابق علمی" title-en="Education History" />
            <BaseButton
              text="افـــــــــــزودن"
              custom-class="complete-info__add-btn"
              @click="openModal('MissionaryAddEducationModal')"
            >
              <template #appendIcon>
                <SvgIcon name="caret-left" :size="14" color="#fff" />
              </template>
            </BaseButton>
          </div>
          <div v-if="store.educationHistory.length > 0" class="complete-info__entries">
            <EntryCard
              v-for="(item, index) in store.educationHistory"
              :key="index"
              :title="educationTitle(item)"
              :subtitle="rangeSubtitle(item.universityName, item.startYear, item.endYear)"
              @edit="openModal('MissionaryAddEducationModal', { entry: item, index })"
            />
          </div>
        </section>

        <section class="complete-info__section">
          <div class="complete-info__section-head">
            <LineTitleBlock title="گواهی ها و تقدیرنامه ها" title-en="Certificates" />
            <BaseButton
              text="افـــــــــــزودن"
              custom-class="complete-info__add-btn"
              @click="openModal('MissionaryAddCertificateModal')"
            >
              <template #appendIcon>
                <SvgIcon name="caret-left" :size="14" color="#fff" />
              </template>
            </BaseButton>
          </div>
          <div v-if="store.certificates.length > 0" class="complete-info__entries">
            <EntryCard
              v-for="(item, index) in store.certificates"
              :key="index"
              :title="item.title"
              :subtitle="rangeSubtitle(item.universityName, item.startYear, item.endYear)"
              @edit="openModal('MissionaryAddCertificateModal', { entry: item, index })"
            />
          </div>
        </section>

        <div class="complete-info__divider" />

        <footer class="complete-info__footer">
          <BaseButton
            text="ذخیره اطلاعات"
            custom-class="complete-info__submit"
            :loading="saveMutation.isPending.value"
            @click="onSave(close)"
          >
            <template #appendIcon>
              <SvgIcon name="arrow-left" :size="18" color="#fff" />
            </template>
          </BaseButton>
        </footer>
      </div>
    </template>
  </BasicModal>

  <AddSkillModal v-if="isModal('MissionaryAddSkillModal')" />
  <AddWorkExperienceModal v-if="isModal('MissionaryAddWorkExperienceModal')" />
  <AddEducationModal v-if="isModal('MissionaryAddEducationModal')" />
  <AddCertificateModal v-if="isModal('MissionaryAddCertificateModal')" />
</template>

<script setup>
import { watch } from 'vue'
import { toast } from 'vue3-toastify'
import Badge from '@/components/Badge.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 { useQueryClient } from '@tanstack/vue-query'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import { useCompleteInfoStore } from '@/features/missionary/store/complete-info'
import EntryCard from '@/features/missionary/components/modals/completeInfo/EntryCard.vue'
import { EDUCATION_DEGREES, SKILL_LEVELS } from '@/features/missionary/constants/complete-info'
import AddSkillModal from '@/features/missionary/components/modals/completeInfo/AddSkillModal.vue'
import AddEducationModal from '@/features/missionary/components/modals/completeInfo/AddEducationModal.vue'
import {
  authKeys,
  useGetRegisterDataQuery,
  useSaveRegisterDataMutation,
} from '@/services/query/auth'
import AddCertificateModal from '@/features/missionary/components/modals/completeInfo/AddCertificateModal.vue'
import AddWorkExperienceModal from '@/features/missionary/components/modals/completeInfo/AddWorkExperienceModal.vue'

defineOptions({ name: 'MissionaryCompleteInfoModal' })

const queryClient = useQueryClient()
const { openModal, isModal } = useModal()

const store = useCompleteInfoStore()
store.reset()

const { data: registerData } = useGetRegisterDataQuery()
watch(
  registerData,
  (value) => {
    if (value && Object.keys(value).length > 0) store.hydrateFromRegisterData(value)
  },
  { immediate: true }
)

const rangeSubtitle = (place, startYear, endYear) => {
  const parts = []
  if (place) parts.push(place)
  if (startYear) parts.push(`از ${startYear} تا ${endYear || 'حالا'}`)
  return parts.join('  |  ')
}

const educationTitle = (item) => {
  const degree = EDUCATION_DEGREES[item.degree] || item.degree || ''
  return [degree, item.fieldOfStudy].filter(Boolean).join(': ')
}

const saveMutation = useSaveRegisterDataMutation()

const onSave = async (close) => {
  try {
    await saveMutation.mutateAsync(store.buildPayload())
    await queryClient.invalidateQueries({ queryKey: authKeys.registerData() })
    toast.success('اطلاعات با موفقیت ذخیره شد.')
    close?.()
  } catch {
    toast.error('ذخیره اطلاعات با خطا مواجه شد.')
  }
}
</script>

<style lang="scss" scoped>
.complete-info {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
  text-align: start;
  padding-block: 0.25rem 0.5rem;

  &__section {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
  }

  &__section-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.75rem;
  }

  &__add-btn {
    min-width: 8rem;
    height: 2.25rem;
    padding: 0 1.25rem;
  }

  &__badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  &__entries {
    display: flex;
    flex-direction: column;
    gap: 0.625rem;
  }

  &__divider {
    border-block-end: 1px solid #ddd;
  }

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

  &__submit {
    min-width: 14rem;
    padding: 0 1.5rem;
  }
}
</style>
