<template>
  <div class="user-form">
    <BoxedIconTitleBlock
      class="user-form__heading"
      :title="isEditMode ? 'ویرایش کاربر' : 'افزودن کاربر جدید'"
      :desc="
        isEditMode ? 'اطلاعات کاربر را به‌روز کنید' : 'در این قسمت می‌توانید کاربر جدید اضافه کنید'
      "
    >
      <template #icon>
        <SvgIcon name="user" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <form class="user-form__form" @submit.prevent="onSubmit">
      <div class="user-form__grid">
        <div class="user-form__main-col">
          <LineTitleBlock title="مشخصات فردی" title-en="Personal Details" />
          <div class="user-form__row">
            <div class="user-form__cell user-form__cell--third">
              <SelectField
                v-model="form.role"
                name="role"
                label="نقش"
                :options="ROLES"
                option-label="label"
                option-value="value"
                :error="errors.role"
                @change="validateAt('role', form.role)"
              />
            </div>
            <div class="user-form__cell user-form__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="user-form__cell user-form__cell--third">
              <DatePickerField
                v-model="form.birthday"
                name="birthday"
                label="تاریخ تولد"
                :max="todayIso"
                :error="errors.birthday"
              />
            </div>
            <div class="user-form__cell user-form__cell--third">
              <TextField
                v-model="form.nationalCode"
                name="nationalCode"
                label="کد ملی"
                inputmode="numeric"
                :convert-digits="true"
                :disabled="isEditMode && !!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="user-form__cell user-form__cell--third">
              <SelectField
                v-model="form.maritalStatus"
                name="maritalStatus"
                label="وضعیت تاهل"
                :options="maritalStatusOptions"
                option-label="label"
                option-value="value"
              />
            </div>
            <div class="user-form__cell user-form__cell--third">
              <SelectField
                v-model="form.gender"
                name="gender"
                label="جنسیت"
                :options="genderOptions"
                option-label="label"
                option-value="value"
              />
            </div>
            <div class="user-form__cell user-form__cell--full">
              <TextareaField
                v-model="form.bio"
                name="bio"
                label="زندگی نامه"
                :row="3"
                :error="errors.bio"
              />
            </div>
          </div>

          <LineTitleBlock title="اطلاعات تماس" title-en="Contact Details" />
          <div class="user-form__row">
            <div class="user-form__cell user-form__cell--third">
              <TextField
                v-model="form.phone"
                name="phone"
                label="شماره تلفن همراه"
                inputmode="numeric"
                :convert-digits="true"
                :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="user-form__cell user-form__cell--third">
              <SelectField
                v-model="form.provinceId"
                name="provinceId"
                label="استان"
                :options="provinces"
                option-label="name"
                option-value="id"
                @change="onProvinceChange"
              />
            </div>
            <div class="user-form__cell user-form__cell--third">
              <SelectField
                v-model="form.cityId"
                name="cityId"
                label="شهر"
                :options="cities"
                option-label="name"
                option-value="id"
                :disabled="!form.provinceId"
              />
            </div>
            <div class="user-form__cell user-form__cell--full">
              <TextareaField
                v-model="form.address"
                name="address"
                label="آدرس محل سکونت"
                :row="isMobile ? 5 : 2"
              />
            </div>
          </div>

          <template v-if="!isEditMode">
            <LineTitleBlock title="رمز عبور" title-en="Password" />
            <div class="user-form__row">
              <div class="user-form__cell user-form__cell--half">
                <PasswordField
                  v-model="form.password"
                  name="password"
                  label="رمز عبور"
                  :error="errors.password"
                  @blur="validateAt('password', form.password)"
                />
              </div>
              <div class="user-form__cell user-form__cell--half">
                <PasswordField
                  v-model="form.passwordConfirmation"
                  name="passwordConfirmation"
                  label="تکرار رمز عبور"
                  :error="errors.passwordConfirmation"
                  @blur="validateAt('passwordConfirmation', form.passwordConfirmation)"
                />
              </div>
            </div>
          </template>

          <div class="user-form__actions">
            <BaseButton
              variant="transparent"
              text="انصراف"
              custom-class="user-form__btn-cancel"
              @click="onCancel"
            />
            <BaseButton
              type="submit"
              :text="isEditMode ? 'ذخیره تغییرات' : 'ثبت کاربر'"
              :loading="submitting"
              custom-class="user-form__btn-submit"
            >
              <template #appendIcon>
                <SvgIcon name="arrow-left" :size="20" color="#fff" />
              </template>
            </BaseButton>
          </div>
        </div>

        <div class="user-form__avatar-col">
          <ImageCropper
            v-model="avatar"
            name="avatar"
            bg-color="#eeeeee"
            @crop="onAvatarCropped"
            @error="onAvatarError"
          />
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import useYup from '@/composables/useYup'
import { useRoute, useRouter } from 'vue-router'
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 { GENDER, MARITAL_STATUS, ROLES } from '@/enums'
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 { useUploadMediaMutation } from '@/services/query/auth'
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 { userAddSchema, userEditSchema } from '@/features/admin/users/schema'
import { useGetCitiesOfProvinceQuery, useGetProvincesQuery } from '@/services/query/common'
import {
  adminUsersKeys,
  useAddAdminUserMutation,
  useAdminUserQuery,
  useUpdateAdminUserMutation,
} from '@/services/query/admin-users'

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

const userId = computed(() => (route.params.id ? Number(route.params.id) : null))
const isEditMode = computed(() => !!userId.value)

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 form = ref({
  role: '',
  name: '',
  birthday: '',
  nationalCode: '',
  maritalStatus: '',
  gender: '',
  bio: '',
  phone: '',
  provinceId: '',
  cityId: '',
  address: '',
  avatarMediaId: null,
  password: '',
  passwordConfirmation: '',
})

const avatar = ref(null)

const schema = isEditMode.value ? userEditSchema : userAddSchema

const { validate, validateAt, errors } = useYup(schema, () => form.value)

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

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

const { data: existingUser } = useAdminUserQuery(userId, {
  enabled: () => !!userId.value,
})

watch(
  existingUser,
  (user) => {
    if (!user) return
    const firstRole = Array.isArray(user.roles) ? user.roles[0] : null
    const roleValue = typeof firstRole === 'object' ? firstRole?.name : firstRole
    form.value = {
      ...form.value,
      role: roleValue || '',
      name: user.name || `${user.firstName || ''} ${user.lastName || ''}`.trim(),
      birthday: user.birthday || '',
      nationalCode: user.nationalCode || '',
      maritalStatus: user.marriageStatus ?? user.profile?.maritalStatus ?? '',
      gender: user.gender ?? user.profile?.gender ?? '',
      bio: user.bio ?? user.profile?.bio ?? '',
      phone: user.phone || '',
      provinceId: user?.province?.id || '',
      cityId: user?.city?.id || '',
      address: typeof user.address === 'string' ? user.address : user.address?.address || '',
      avatarMediaId: null,
    }
    initialNationalCode.value = user.nationalCode || ''
    if (user.avatarUrl) {
      avatar.value = { url: user.avatarUrl }
    }
  },
  { 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 {
    /* error handled by global handler */
  }
}

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

const addMutation = useAddAdminUserMutation()
const updateMutation = useUpdateAdminUserMutation()

const submitting = computed(() => addMutation.isPending.value || updateMutation.isPending.value)

// Maps the form to the backend Update User contract:
// { name, roles, province_id, city_id, marriage_status, birthday, gender,
//   address, national_code } (snake-case conversion happens in the http layer),
// plus phone/bio/avatar that the form also edits.
const buildUpdatePayload = () => {
  return {
    name: form.value.name,
    roles: form.value.role ? [form.value.role] : [],
    provinceId: form.value.provinceId || null,
    cityId: form.value.cityId || null,
    marriageStatus: form.value.maritalStatus || null,
    birthday: form.value.birthday || null,
    gender: form.value.gender || null,
    address: form.value.address || '',
    nationalCode: form.value.nationalCode,
    phone: form.value.phone,
    bio: form.value.bio || '',
    avatarMediaId: form.value.avatarMediaId || null,
  }
}

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  if (isEditMode.value) {
    await updateMutation.mutateAsync({ id: userId.value, payload: buildUpdatePayload() })
  } else {
    await addMutation.mutateAsync(payload)
  }
  await queryClient.invalidateQueries({ queryKey: adminUsersKeys.all })
  router.push({ name: 'admin-users' })
}

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

<style lang="scss" scoped>
.user-form {
  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: 8fr 4fr;
    }

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

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

  &__main-col {
    @media (min-width: 1024px) {
      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;
    gap: 0.625rem;
    margin-top: 1rem;
  }

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

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