<template>
  <div class="edit-profile">
    <BoxedIconTitleBlock
      class="edit-profile__heading"
      title="ویرایش پروفایل"
      desc="در این قسمت می‌توانید پروفایل خود را به‌روز کنید."
    >
      <template #icon>
        <SvgIcon name="user" :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"
            @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.firstName"
                name="firstName"
                label="نام"
                :error="errors.firstName"
                @blur="validateAt('firstName', form.firstName)"
              >
                <template #appendIcon>
                  <SvgIcon name="user" :size="20" color="var(--color-thd-gray)" />
                </template>
              </TextField>
            </div>
            <div class="edit-profile__cell edit-profile__cell--third">
              <TextField
                v-model="form.lastName"
                name="lastName"
                label="نام خانوادگی"
                :error="errors.lastName"
                @blur="validateAt('lastName', form.lastName)"
              >
                <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.birthDate"
                name="birthDate"
                label="تاریخ تولد"
                :max="todayIso"
                :error="errors.birthDate"
              />
            </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.maritalStatus"
                name="maritalStatus"
                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--full">
              <TextareaField v-model="form.bio" name="bio" label="زندگی نامه" :row="3" />
            </div>
          </div>

          <LineTitleBlock title="اطلاعات تماس" title-en="Contact Details" />
          <div class="edit-profile__row">
            <div class="edit-profile__cell edit-profile__cell--third">
              <TextField
                v-model="form.phoneNumber"
                name="phoneNumber"
                label="شماره تلفن همراه"
                inputmode="numeric"
                :convert-digits="true"
                :disabled="!!initialPhoneNumber"
                :error="errors.phoneNumber"
                @blur="validateAt('phoneNumber', form.phoneNumber)"
              >
                <template #appendIcon>
                  <SvgIcon name="phone" :size="20" color="var(--color-thd-gray)" />
                </template>
              </TextField>
            </div>
            <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--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="form.password"
                name="password"
                label="رمز عبور"
                :error="errors.password"
                @blur="validateAt('password', form.password)"
              />
            </div>
            <div class="edit-profile__cell edit-profile__cell--half">
              <PasswordField
                v-model="form.passwordConfirmation"
                name="passwordConfirmation"
                label="تکرار رمز عبور"
                :error="errors.passwordConfirmation"
                @blur="validateAt('passwordConfirmation', form.passwordConfirmation)"
              />
            </div>
          </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 { 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 PasswordField from '@/components/form/PasswordField.vue'
import DatePickerField from '@/components/form/DatePickerField.vue'
import { studentProfileSchema } from '@/features/student/profile/schema'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import { useGetCitiesOfProvinceQuery, useGetProvincesQuery } from '@/services/query/common'
import {
  authKeys,
  useGetProfileQuery,
  useUpdateProfileMutation,
  useUploadTemporaryMutation,
} 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 { data: provinces = ref([]) } = useGetProvincesQuery()

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

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

const form = ref({
  firstName: '',
  lastName: '',
  birthDate: '',
  nationalCode: '',
  maritalStatus: '',
  gender: '',
  bio: '',
  phoneNumber: '',
  provinceId: '',
  cityId: '',
  address: '',
  avatarId: null,
  password: '',
  passwordConfirmation: '',
})

const avatar = ref(null)

const schema = studentProfileSchema

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

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

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

const { data: profile } = useGetProfileQuery()

watch(profile, (user) => {
  if (!user) return
  form.value = {
    ...form.value,
    firstName: user.firstName || '',
    lastName: user.lastName || '',
    birthDate: user.profile?.birthDate || '',
    nationalCode: user.nationalCode || '',
    maritalStatus: user.profile?.maritalStatus || '',
    gender: user.profile?.gender || '',
    bio: user.profile?.bio || '',
    phoneNumber: user.phoneNumber || '',
    provinceId: user.address?.province?.id || '',
    cityId: user.address?.city?.id || '',
    address: user.address?.address || '',
    avatarId: user.profile?.avatarId || null,
  }
  initialNationalCode.value = user.nationalCode || ''
  initialPhoneNumber.value = user.phoneNumber || ''
  if (user.avatarUrl) avatar.value = { url: user.avatarUrl }
})

const uploadMutation = useUploadTemporaryMutation()

const onAvatarCropped = async (file) => {
  try {
    const formData = objectToFormData({ file, subType: '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.avatarId = payload?.uploadId || payload?.id
  } catch {
    /* handled globally */
  }
}

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

const updateMutation = useUpdateProfileMutation()

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  if (!payload.password) {
    delete payload.password
    delete payload.passwordConfirmation
  }
  await updateMutation.mutateAsync(payload)
  await queryClient.invalidateQueries({ queryKey: authKeys.profile() })
  toast.success('پروفایل با موفقیت به‌روز شد')
  router.push({ name: 'student-dashboard' })
}

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: grid;
    grid-template-columns: 1fr;
    gap: 1rem;

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

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

  &__avatar-col {
    order: 2;

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

  &__main-col {
    order: 1;

    @media (min-width: 1024px) {
      order: 2;
      padding-inline-start: 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;
    gap: 0.625rem;
    margin-top: 1rem;
  }

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

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