<template>
  <form class="personal-info" @submit.prevent="onSubmit">
    <div class="personal-info__grid">
      <div class="personal-info__avatar-col">
        <ImageCropper
          v-model="avatar"
          name="avatar"
          bg-color="#eeeeee"
          :error="errors.avatar"
          @crop="onAvatarCropped"
          @error="onAvatarError"
        />
      </div>

      <div class="personal-info__main-col">
        <LineTitleBlock title="مشخصات فردی" title-en="Personal Details" />
        <div class="personal-info__row">
          <div class="personal-info__cell">
            <TextField
              v-model="form.name"
              name="name"
              label="نام و نام خانوادگی"
              :error="errors.name"
              @blur="validateAt('name', form.name)"
            >
              <template #appendIcon>
                <SvgIcon name="user" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <DatePickerField
              v-model="form.birthday"
              name="birthday"
              label="تاریخ تولد"
              :max="maxBirthDate"
              :error="errors.birthday"
            />
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.nationalCode"
              name="nationalCode"
              label="کد ملی"
              inputmode="numeric"
              :convert-digits="true"
              :disabled="!!initialNationalCode"
              :error="errors.nationalCode"
              @blur="validateAt('nationalCode', form.nationalCode)"
            >
              <template #appendIcon>
                <SvgIcon name="user" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <SelectField
              v-model="form.maritalStatus"
              name="maritalStatus"
              label="وضعیت تاهل"
              :options="maritalStatusOptions"
              option-label="label"
              option-value="value"
              :error="errors.maritalStatus"
            />
          </div>
          <div class="personal-info__cell">
            <SelectField
              v-model="form.gender"
              name="gender"
              label="جنسیت"
              :options="genderOptions"
              option-label="label"
              option-value="value"
              :error="errors.gender"
            />
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.childrenCount"
              name="childrenCount"
              label="تعداد فرزند"
              inputmode="numeric"
              :convert-digits="true"
              :error="errors.childrenCount"
              @blur="validateAt('childrenCount', form.childrenCount)"
            >
              <template #appendIcon>
                <SvgIcon name="users-three" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.seminaryCode"
              name="seminaryCode"
              label="کد حوزوی"
              inputmode="numeric"
              :convert-digits="true"
              :error="errors.seminaryCode"
              @blur="validateAt('seminaryCode', form.seminaryCode)"
            >
              <template #appendIcon>
                <SvgIcon name="graduation-cap" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.seminaryServiceCenterCode"
              name="seminaryServiceCenterCode"
              label="کد مرکز خدمات حوزه"
              inputmode="numeric"
              :convert-digits="true"
              :error="errors.seminaryServiceCenterCode"
              @blur="validateAt('seminaryServiceCenterCode', form.seminaryServiceCenterCode)"
            >
              <template #appendIcon>
                <SvgIcon name="check-square" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
        </div>

        <LineTitleBlock title="اطلاعات تماس" title-en="Contact Details" />
        <div class="personal-info__row">
          <div class="personal-info__cell personal-info__cell--full-sm">
            <TextField
              v-model="form.phone"
              name="phone"
              label="شماره تلفن همراه"
              inputmode="numeric"
              :convert-digits="true"
              :disabled="!!initialPhone"
              :error="errors.phone"
              @blur="validateAt('phone', form.phone)"
            >
              <template #appendIcon>
                <SvgIcon name="phone" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.virtualPhoneNumber"
              name="virtualPhoneNumber"
              label="شماره تلفن مجازی"
              inputmode="numeric"
              :convert-digits="true"
              :error="errors.virtualPhoneNumber"
              @blur="validateAt('virtualPhoneNumber', form.virtualPhoneNumber)"
            >
              <template #appendIcon>
                <SvgIcon name="phone" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <TextField
              v-model="form.postalCode"
              name="postalCode"
              label="کد پستی"
              inputmode="numeric"
              :convert-digits="true"
              :error="errors.postalCode"
              @blur="validateAt('postalCode', form.postalCode)"
            >
              <template #appendIcon>
                <SvgIcon name="map-pin-simple-area" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextField>
          </div>
          <div class="personal-info__cell">
            <SelectField
              v-model="form.provinceId"
              name="provinceId"
              label="استان"
              :options="provinces"
              option-label="name"
              option-value="id"
              :error="errors.provinceId"
              @change="onProvinceChange"
            />
          </div>
          <div class="personal-info__cell">
            <SelectField
              v-model="form.cityId"
              name="cityId"
              label="شهر"
              :options="cities"
              option-label="name"
              option-value="id"
              :disabled="!form.provinceId"
              :error="errors.cityId"
            />
          </div>
          <div class="personal-info__cell personal-info__cell--full">
            <TextareaField
              v-model="form.address"
              name="address"
              label="آدرس محل سکونت"
              :row="isMobile ? 5 : 1"
              :error="errors.address"
              @blur="validateAt('address', form.address)"
            >
              <template #appendIcon>
                <SvgIcon name="file" :size="20" color="var(--color-thd-gray)" />
              </template>
            </TextareaField>
          </div>
        </div>
      </div>
    </div>

    <div class="personal-info__divider" />

    <StepActions
      :show-back="false"
      :loading="
        uploadMutation.isPending.value ||
        updateProfileMutation.isPending.value ||
        saveRegisterMutation.isPending.value
      "
    />
  </form>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import useYup from '@/composables/useYup'
import useAuth from '@/composables/useAuth'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { useQueryClient } from '@tanstack/vue-query'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import ImageCropper from '@/components/form/ImageCropper.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import TextareaField from '@/components/form/TextareaField.vue'
import DatePickerField from '@/components/form/DatePickerField.vue'
import { GENDER, MARITAL_STATUS, STUDENT_REGISTRATION } from '@/enums'
import { personalInformationSchema } from '@/features/auth/schema/student-register'
import StepActions from '@/features/auth/components/studentRegister/StepActions.vue'
import { useStudentRegistrationStore } from '@/features/auth/store/student-registration'
import { useGetCitiesOfProvinceQuery, useGetProvincesQuery } from '@/services/query/common'
import {
  authKeys,
  useSaveRegisterDataMutation,
  useUpdateProfileMutation,
  useUploadMediaMutation,
} from '@/services/query/auth'

const store = useStudentRegistrationStore()
const { user } = useAuth()
const queryClient = useQueryClient()

const isMobile = ref(window.innerWidth < 768)
const onResize = () => {
  isMobile.value = window.innerWidth < 768
}
onMounted(() => window.addEventListener('resize', onResize))
onBeforeUnmount(() => window.removeEventListener('resize', onResize))

const maritalStatusOptions = Object.entries(MARITAL_STATUS).map(([value, label]) => ({
  value,
  label,
}))
const genderOptions = Object.entries(GENDER).map(([value, label]) => ({ value, label }))

const maxBirthDate = (() => {
  const d = new Date()
  d.setFullYear(d.getFullYear() - 15)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
})()

const initialPhone = ref(user.value?.phone || store.personal.phone || '')
const initialNationalCode = ref(user.value?.nationalCode || store.personal.nationalCode || '')

const initialAvatar =
  store.personal.avatar || (user.value?.avatarUrl ? { url: user.value.avatarUrl } : null)

const form = ref({
  name: user.value?.name || store.personal.name || '',
  birthday: user.value?.birthday || store.personal.birthday || '',
  nationalCode: initialNationalCode.value,
  maritalStatus: user.value?.marriageStatus || store.personal.maritalStatus || '',
  gender: user.value?.gender || store.personal.gender || '',
  phone: initialPhone.value,
  provinceId: user.value?.provinceId || store.personal.provinceId || null,
  cityId: user.value?.cityId || store.personal.cityId || null,
  address:
    (typeof user.value?.address === 'string' && user.value.address) || store.personal.address || '',
  postalCode: store.personal.postalCode || '',
  virtualPhoneNumber: store.personal.virtualPhoneNumber || '',
  seminaryCode: store.personal.seminaryCode || '',
  seminaryServiceCenterCode: store.personal.seminaryServiceCenterCode || '',
  childrenCount: store.personal.childrenCount ?? '',
  avatar: initialAvatar,
  avatarId: store.personal.avatarId || '',
})

watch(form, (value) => store.updateSection('personal', value), { deep: true })

const avatar = ref(initialAvatar)

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

const { data: provinces = ref([]) } = useGetProvincesQuery()

const provinceIdRef = ref(form.value.provinceId)
const { data: cities = ref([]) } = useGetCitiesOfProvinceQuery(provinceIdRef, {
  enabled: () => !!provinceIdRef.value,
})

const onProvinceChange = (provinceId) => {
  provinceIdRef.value = provinceId
  form.value.cityId = null
}

watch(
  () => form.value.provinceId,
  (val) => {
    provinceIdRef.value = val
  }
)

const uploadMutation = useUploadMediaMutation()

const onAvatarCropped = async (file) => {
  try {
    const fd = objectToFormData({ file, purpose: 'avatar', context: 'verification' })
    const response = await uploadMutation.mutateAsync(fd)
    const payload = response?.data ?? response
    const value = { url: payload?.url, uploadId: payload?.uploadId || payload?.id, ...payload }
    avatar.value = value
    form.value.avatar = value
    form.value.avatarId = value.uploadId
  } catch {
    toast.error('بارگذاری تصویر با خطا مواجه شد')
  }
}

const onAvatarError = (msg) => toast.error(msg)

const updateProfileMutation = useUpdateProfileMutation()
const saveRegisterMutation = useSaveRegisterDataMutation()

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  const next = { ...payload, avatar: form.value.avatar }
  // Personal info maps to the user model and is persisted via PATCH /me.
  // (http auto-converts camelCase → snake_case: birthday, national_code, …)
  const body = {
    name: payload.name,
    birthday: payload.birthday,
    nationalCode: payload.nationalCode,
    marriageStatus: payload.maritalStatus,
    gender: payload.gender,
    phone: payload.phone,
    provinceId: payload.provinceId,
    cityId: payload.cityId,
    address: payload.address,
    ...(form.value.avatar?.uploadId
      ? { avatarMediaId: Number.parseInt(form.value.avatar.uploadId) }
      : {}),
  }
  await updateProfileMutation.mutateAsync(body)
  await saveRegisterMutation.mutateAsync({
    postalCode: payload.postalCode,
    virtualPhoneNumber: payload.virtualPhoneNumber,
    seminaryCode: payload.seminaryCode,
    seminaryServiceCenterCode: payload.seminaryServiceCenterCode,
    childrenCount: payload.childrenCount,
  })
  await queryClient.invalidateQueries({ queryKey: authKeys.me() })
  store.personal = { ...store.personal, ...next }
  store.markStepAsCompleted(STUDENT_REGISTRATION.PERSONAL_INFORMATION)
  store.goToNextStep()
}
</script>

<style lang="scss" scoped>
.personal-info {
  display: flex;
  flex-direction: column;

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

    @media (min-width: 1024px) {
      grid-template-columns: 3fr 9fr;
    }
  }

  &__avatar-col {
    // Uploader stays first: top of the stack on mobile, left column on desktop.
    order: 1;

    @media (min-width: 1024px) {
      padding: 0.5rem;
    }
  }

  &__main-col {
    order: 2;

    @media (min-width: 1024px) {
      padding-inline-start: 1.25rem;
    }
  }

  &__row {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.5rem 0.625rem;
    margin-bottom: 1rem;

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

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

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

  &__cell--full-sm {
    @media (max-width: 767px) {
      grid-column: 1 / -1;
    }
  }

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