<!-- src/pages/UserProfile.vue -->
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter }          from 'vue-router'
import { useAuthStore }                 from '@/stores/Auth.js'
import { useRoleStore }                 from '@/stores/RoleStore.js'

const router     = useRouter()
const route      = useRoute()
const authStore  = useAuthStore()
const roleStore  = useRoleStore()

/* ------------------------------------------------------ */
/* 1. Данные пользователя + форма                         */
/* ------------------------------------------------------ */
const userData = ref(null)

const form = ref({
  id: null,
  last_name:   '',
  first_name:  '',
  middle_name: '',
  position:    '',
  birthday:    '',
  role_id:     null,
  password: '',
  password_confirmation: '',
})

/* ------------------------------------------------------ */
/* 2. Загрузка ролей и профиля                            */
/* ------------------------------------------------------ */
async function fetchUser(id) {
  const { response, error } = await authStore.getUserInfo(id)
  if (error) {
    console.error(error)
    return
  }
  userData.value = response.data.user
}

onMounted(async () => {
  // подгружаем роли единожды
  if (!roleStore.roles.length) {
    await roleStore.fetchRoles()
  }
  // грузим пользователя
  await fetchUser(route.params.id)
})

/* ------------------------------------------------------ */
/* 3. Список ролей для селекта                            */
/* ------------------------------------------------------ */
const rolesForSelect = computed(() => roleStore.roles)

/* ------------------------------------------------------ */
/* 4. Синхронизация формы с userData                      */
/* ------------------------------------------------------ */
watch(
    () => userData.value,
    (u) => {
      if (!u) return
      form.value = {
        id         : u.id,
        last_name  : u.last_name   ?? '',
        first_name : u.first_name  ?? '',
        middle_name: u.middle_name ?? '',
        position   : u.position    ?? '',
        birthday   : u.birthday    ?? '',
        role_id    : u.role?.id    ?? null,
        password: '',
        password_confirmation: '',
      }
    },
    { immediate: true }
)

/* ------------------------------------------------------ */
/* 5. Сохранение                                          */
/* ------------------------------------------------------ */
async function submit() {
  if (form.value.password || form.value.password_confirmation) {
    if (form.value.password.length < 8) {
      console.error('Пароль слишком короткий')
      return
    }
    if (form.value.password !== form.value.password_confirmation) {
      console.error('Пароли не совпадают')
      return
    }
  }
  const payload = { ...form.value }
  // не шлём пустые password поля
  if (!payload.password) {
    delete payload.password
    delete payload.password_confirmation
  }
  const { error } = await authStore.changeUserInfo(form.value.id, payload)
  if (error) {
    console.error(error)
    return
  }
  router.push({ name: 'users-list' })
}
</script>

<template>
  <div class="container py-4">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card shadow-sm">
          <div class="card-body">
            <h3 class="card-title text-center mb-4">Профиль пользователя</h3>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Имя:</label>
              <input v-model="form.first_name"  type="text" class="form-control" />
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Отчество:</label>
              <input v-model="form.middle_name" type="text" class="form-control" />
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Фамилия:</label>
              <input v-model="form.last_name"  type="text" class="form-control" />
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Должность:</label>
              <input v-model="form.position" type="text" class="form-control" />
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Дата рождения:</label>
              <input v-model="form.birthday" type="date" class="form-control" />
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0" for="role_id">Роль:</label>
              <select v-model="form.role_id" id="role_id" class="form-select" required>
                <option value="" disabled>Выберите роль</option>
                <option v-for="role in rolesForSelect" :key="role.id" :value="role.id">
                  {{ role.name }}
                </option>
              </select>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Новый пароль:</label>
              <input
                  v-model="form.password"
                  type="password"
                  class="form-control"
                  placeholder="не менее 8 символов"
              />
            </div>
            <div class="mb-3 d-flex align-items-center">
              <label class="w-150 flex-shrink-0">Подтвердите пароль:</label>
              <input
                  v-model="form.password_confirmation"
                  type="password"
                  class="form-control"
              />
            </div>

            <div class="d-flex justify-content-end">
              <button class="btn btn-primary" type="button" @click="submit">
                Сохранить
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.w-150 { width: 150px; }
</style>
