<template>
  <div class="edit-profile">
    <BoxedIconTitleBlock
      class="edit-profile__heading"
      title="ویرایش پروفایل"
      desc="در این قسمت می‌توانید پروفایل خود را به‌روز کنید."
    >
      <template #icon>
        <SvgIcon name="user-circle-check" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <form class="edit-profile__form" @submit.prevent="onSubmit">
      <div class="edit-profile__grid">
        <div class="edit-profile__avatar-col">
          <ImageCropper
            v-model="avatar"
            name="avatar"
            bg-color="#eeeeee"
            helper-text="برای آپلود تصویر جدید لطفا روی دکمه بالا کلیک کنید."
            @crop="onAvatarCropped"
            @error="onAvatarError"
          />
        </div>

        <div class="edit-profile__main-col">
          <LineTitleBlock title="مشخصات فردی" title-en="Personal Details" />
          <div class="edit-profile__row">
            <div class="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--third">
              <DatePickerField
                v-model="form.birthday"
                name="birthday"
                label="تاریخ تولد"
                :max="todayIso"
                :error="errors.birthday"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <TextField
                v-model="form.phone"
                name="phone"
                label="شماره تلفن همراه"
                inputmode="numeric"
                :convert-digits="true"
                :disabled="!!initialPhoneNumber"
                :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="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--third">
              <SelectField
                v-model="form.marriageStatus"
                name="marriageStatus"
                label="وضعیت تاهل"
                :options="maritalStatusOptions"
                option-label="label"
                option-value="value"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <SelectField
                v-model="form.gender"
                name="gender"
                label="جنسیت"
                :options="genderOptions"
                option-label="label"
                option-value="value"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--third">
              <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="Address Details" />
          <div class="edit-profile__row">
            <div class="edit-profile__cell edit-profile__cell--third">
              <SelectField
                v-model="form.provinceId"
                name="provinceId"
                label="استان"
                :options="provinces"
                option-label="name"
                option-value="id"
                @change="onProvinceChange"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <SelectField
                v-model="form.cityId"
                name="cityId"
                label="شهر"
                :options="cities"
                option-label="name"
                option-value="id"
                :disabled="!form.provinceId"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <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="edit-profile__cell edit-profile__cell--full">
              <TextareaField
                v-model="form.address"
                name="address"
                label="آدرس محل سکونت"
                :row="isMobile ? 5 : 2"
              />
            </div>
          </div>

          <LineTitleBlock title="رمز عبور" title-en="Password" />
          <div class="edit-profile__row">
            <div class="edit-profile__cell edit-profile__cell--half">
              <PasswordField
                v-model="passwordForm.password"
                name="password"
                label="رمز عبور"
                :error="passwordErrors.password"
                @blur="validateAtPassword('password', passwordForm.password)"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--half">
              <PasswordField
                v-model="passwordForm.passwordConfirmation"
                name="passwordConfirmation"
                label="تکرار رمز عبور"
                :error="passwordErrors.passwordConfirmation"
                @blur="
                  validateAtPassword('passwordConfirmation', passwordForm.passwordConfirmation)
                "
              />
            </div>
          </div>

          <div class="edit-profile__password-actions">
            <BaseButton
              type="button"
              text="تغییر رمز عبور"
              :loading="resetPasswordMutation.isPending.value"
              custom-class="edit-profile__btn-reset"
              @click="onResetPassword"
            >
              <template #appendIcon>
                <SvgIcon name="arrows-clockwise" :size="20" color="#fff" />
              </template>
            </BaseButton>
          </div>

          <div class="edit-profile__actions">
            <BaseButton
              variant="transparent"
              text="منصرف شدم"
              custom-class="edit-profile__btn-cancel"
              @click="onCancel"
            >
              <template #prependIcon>
                <SvgIcon name="caret-right" :size="14" color="var(--color-sec-gray)" />
              </template>
            </BaseButton>
            <BaseButton
              type="submit"
              text="تایید اطلاعات"
              :loading="updateMutation.isPending.value"
              custom-class="edit-profile__btn-submit"
            >
              <template #appendIcon>
                <SvgIcon name="arrow-left" :size="20" color="#fff" />
              </template>
            </BaseButton>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import { useRouter } from 'vue-router'
import useYup from '@/composables/useYup'
import { GENDER, MARITAL_STATUS } from '@/enums'
import { useQueryClient } from '@tanstack/vue-query'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import ImageCropper from '@/components/form/ImageCropper.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import { applyValidationErrors } from '@/utils/error-handler'
import TextareaField from '@/components/form/TextareaField.vue'
import PasswordField from '@/components/form/PasswordField.vue'
import DatePickerField from '@/components/form/DatePickerField.vue'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import { useGetCitiesOfProvinceQuery, useGetProvincesQuery } from '@/services/query/common'
import { studentProfileSchema, studentResetPasswordSchema } from '@/features/student/profile/schema'
import {
  authKeys,
  useGetMeQuery,
  useGetRegisterDataQuery,
  useSaveRegisterDataMutation,
  useUpdateProfileMutation,
  useUploadMediaMutation,
} from '@/services/query/auth'

const router = useRouter()
const queryClient = useQueryClient()

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

const todayIso = new Date().toISOString()

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

const initialNationalCode = ref('')
const initialPhoneNumber = ref('')

const form = ref({
  name: '',
  birthday: '',
  nationalCode: '',
  marriageStatus: '',
  gender: '',
  phone: '',
  provinceId: '',
  cityId: '',
  address: '',
  postalCode: '',
  virtualPhoneNumber: '',
  seminaryCode: '',
  seminaryServiceCenterCode: '',
  childrenCount: '',
  avatarMediaId: null,
})

const passwordForm = ref({
  password: '',
  passwordConfirmation: '',
})

const avatar = ref(null)

const schema = studentProfileSchema

const { validate, validateAt, errors } = useYup(schema)
const {
  validate: validatePassword,
  validateAt: validateAtPassword,
  errors: passwordErrors,
  resetErrors: resetPasswordErrors,
  setError: setPasswordError,
} = useYup(studentResetPasswordSchema, () => ({
  ...passwordForm.value,
  phone: form.value.phone,
}))

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

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

const onProvinceChange = () => {
  form.value.cityId = ''
}

const { data: profile } = useGetMeQuery()

watch(
  profile,
  (user) => {
    if (!user) return
    const fullName =
      user.name || [user.firstName, user.lastName].filter(Boolean).join(' ').trim() || ''
    const phone = user.phone || user.phoneNumber || ''
    form.value = {
      ...form.value,
      name: fullName,
      birthday: user?.birthday || '',
      nationalCode: user.nationalCode || '',
      marriageStatus: user?.marriageStatus || '',
      gender: user?.gender || '',
      phone,
      provinceId: user?.province?.id || '',
      cityId: user?.city?.id || '',
      address: user?.address || '',
      avatarMediaId: user?.avatarMediaId || null,
    }
    initialNationalCode.value = user.nationalCode || ''
    initialPhoneNumber.value = phone
    if (user.avatarUrl) avatar.value = { url: user.avatarUrl }
  },
  { immediate: true }
)

const { data: registerData } = useGetRegisterDataQuery()

watch(
  registerData,
  (data) => {
    if (!data) return
    form.value = {
      ...form.value,
      postalCode: data.postalCode || '',
      virtualPhoneNumber: data.virtualPhoneNumber || '',
      seminaryCode: data.seminaryCode || '',
      seminaryServiceCenterCode: data.seminaryServiceCenterCode || '',
      childrenCount: data.childrenCount ?? '',
    }
  },
  { immediate: true }
)

const uploadMutation = useUploadMediaMutation()

const onAvatarCropped = async (file) => {
  try {
    const formData = objectToFormData({ file, purpose: 'avatar', context: 'user' })
    const response = await uploadMutation.mutateAsync(formData)
    const payload = response?.data ?? response
    avatar.value = { url: payload?.url, uploadId: payload?.uploadId, ...payload }
    form.value.avatarMediaId = payload?.uploadId || payload?.id
  } catch {
    /* handled globally */
  }
}

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

const updateMutation = useUpdateProfileMutation()
const saveRegisterDataMutation = useSaveRegisterDataMutation()
const resetPasswordMutation = useUpdateProfileMutation()

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  // Backend PATCH /me accepts: name, email, phone, avatar_media_id.
  // Other UI-only fields (province/city/address/birthday/…) are not in
  // the backend Postman doc and are dropped here. Password is handled
  // separately via POST /reset-password.
  const body = {
    ...(payload.name ? { name: payload.name } : {}),
    ...(payload.phone ? { phone: payload.phone } : {}),
    ...(payload.email ? { email: payload.email } : {}),
    ...(payload.avatarMediaId ? { avatarMediaId: payload.avatarMediaId } : {}),
  }
  await updateMutation.mutateAsync(body)
  await saveRegisterDataMutation.mutateAsync({
    postalCode: payload.postalCode || '',
    virtualPhoneNumber: payload.virtualPhoneNumber || '',
    seminaryCode: payload.seminaryCode || '',
    seminaryServiceCenterCode: payload.seminaryServiceCenterCode || '',
    childrenCount:
      payload.childrenCount == null || payload.childrenCount === ''
        ? ''
        : Number(payload.childrenCount),
  })
  await queryClient.invalidateQueries({ queryKey: authKeys.me() })
  await queryClient.invalidateQueries({ queryKey: authKeys.registerData() })
  toast.success('پروفایل با موفقیت به‌روز شد')
  router.push({ name: 'student-dashboard' })
}

const onResetPassword = async () => {
  resetPasswordErrors()
  const { isValid, payload } = await validatePassword({
    phone: form.value.phone,
    password: passwordForm.value.password,
    passwordConfirmation: passwordForm.value.passwordConfirmation,
  })
  if (!isValid) return
  try {
    await resetPasswordMutation.mutateAsync({
      password: payload.password,
      passwordConfirmation: payload.passwordConfirmation,
    })
    passwordForm.value.password = ''
    passwordForm.value.passwordConfirmation = ''
    resetPasswordErrors()
    toast.success('رمز عبور با موفقیت تغییر یافت')
  } catch (error) {
    applyValidationErrors(error, setPasswordError)
  }
}

const onCancel = () => router.push({ name: 'student-dashboard' })
</script>

<style lang="scss" scoped>
.edit-profile {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__form {
    background: rgba(255, 255, 255, 60%);
    padding: 1rem;
    border-radius: 1rem;
  }

  &__grid {
    display: flex;
    flex-direction: column;
    gap: 1rem;

    @media (min-width: 1024px) {
      display: grid;
      grid-template-columns: 8fr 4fr;
    }

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

  &__avatar-col {
    order: 1;

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

  &__main-col {
    order: 2;

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

  &__row {
    display: flex;
    flex-flow: column wrap;
    gap: 0.5rem;
    align-items: stretch;
    margin-bottom: 0.5rem;

    @media (min-width: 768px) {
      flex-direction: row;
    }
  }

  &__cell {
    width: 100%;

    &--third {
      @media (min-width: 768px) {
        width: 49%;
      }

      @media (min-width: 1280px) {
        width: 32.3%;
      }
    }

    &--half {
      @media (min-width: 768px) {
        width: 49%;
      }
    }

    &--full {
      width: 100%;
    }
  }

  &__actions {
    display: flex;
    justify-content: flex-end;
    justify-content: space-between;
    margin-top: 1rem;
  }

  &__password-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 0.5rem;
    margin-bottom: 1rem;
  }

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

  &__btn-submit {
    min-width: 12rem;
  }

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