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

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

/* ------------------------------------------------------ */
/* 1. Роли: берём из общего стора                         */
/* ------------------------------------------------------ */
onMounted(async () => {
  if (!roleStore.roles.length) {
    await roleStore.fetchRoles()
  }

  // сразу сгенерируем временный пароль
  const pwd                 = generateTemporaryPassword()
  form.value.password        = pwd
  form.value.password_confirmation = pwd
})

const roles = computed(() => roleStore.roles)   // [{id, name}, …]

/* ------------------------------------------------------ */
/* 2. Форма                                               */
/* ------------------------------------------------------ */
const form = ref({
  first_name: '',
  middle_name: '',
  last_name: '',
  login: '',
  role_id: null,
  position: '',
  birthday: '',
  password: '',
  password_confirmation: '',
})

/* генерация логина автоматически */
watch(
    () => [form.value.first_name, form.value.last_name],
    () => {
      form.value.login = generateLogin(form.value.first_name, form.value.last_name)
    }
)

/* ------------------------------------------------------ */
/* 3. Сообщения и ошибки                                  */
/* ------------------------------------------------------ */
const message = ref('')
const errors  = ref({})

/* ------------------------------------------------------ */
/* 4. Отправка                                            */
/* ------------------------------------------------------ */
async function registration() {
  errors.value  = {}
  message.value = ''

  const { response, error } = await authStore.register(form.value)

  if (response && (response.status === 200 || response.status === 201)) {
    message.value = response.data.message || 'Регистрация прошла успешно!'

    // сбрасываем форму
    form.value = {
      first_name: '',
      middle_name: '',
      last_name: '',
      login: '',
      role_id: null,
      position: '',
      birthday: '',
      password: '',
      password_confirmation: '',
    }

    router.push({ name: 'users-list' })
  } else if (error) {
    const err = error.response?.data?.errors
    if (err) {
      errors.value = err
    } else {
      message.value = 'Ошибка при регистрации.'
    }
  }
}
</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>

            <form @submit.prevent="registration">
              <!-- Фамилия -->
              <div class="mb-3">
                <label for="last_name" class="form-label">Фамилия:</label>
                <input v-model="form.last_name" id="last_name" type="text" class="form-control" required />
                <div v-if="errors.last_name" class="text-danger">{{ errors.last_name[0] }}</div>
              </div>

              <!-- Имя -->
              <div class="mb-3">
                <label for="first_name" class="form-label">Имя:</label>
                <input v-model="form.first_name" id="first_name" type="text" class="form-control" required />
                <div v-if="errors.first_name" class="text-danger">{{ errors.first_name[0] }}</div>
              </div>

              <!-- Отчество -->
              <div class="mb-3">
                <label for="middle_name" class="form-label">Отчество:</label>
                <input v-model="form.middle_name" id="middle_name" type="text" class="form-control" required />
                <div v-if="errors.middle_name" class="text-danger">{{ errors.middle_name[0] }}</div>
              </div>

              <!-- Логин (автогенерация) -->
              <div class="mb-3">
                <label for="login" class="form-label">Логин:</label>
                <input v-model="form.login" id="login" type="text" class="form-control" disabled />
                <div v-if="errors.login" class="text-danger">{{ errors.login[0] }}</div>
              </div>

              <!-- Роль -->
              <div class="mb-3">
                <label for="role_id" class="form-label">Роль:</label>
                <select v-model="form.role_id" id="role_id" class="form-select" required>
                  <option value="" disabled>Выберите роль</option>
                  <option v-for="role in roles" :key="role.id" :value="role.id">
                    {{ role.name }}
                  </option>
                </select>
                <div v-if="errors.role_id" class="text-danger">{{ errors.role_id[0] }}</div>
              </div>

              <!-- Должность -->
              <div class="mb-3">
                <label for="position" class="form-label">Должность:</label>
                <input v-model="form.position" id="position" type="text" class="form-control" required />
                <div v-if="errors.position" class="text-danger">{{ errors.position[0] }}</div>
              </div>

              <!-- Дата рождения -->
              <div class="mb-3">
                <label for="birthday" class="form-label">Дата рождения:</label>
                <input v-model="form.birthday" id="birthday" type="date" class="form-control" required />
                <div v-if="errors.birthday" class="text-danger">{{ errors.birthday[0] }}</div>
              </div>

              <!-- Пароль -->
              <div class="mb-3">
                <label for="password" class="form-label">Пароль:</label>
                <input v-model="form.password" id="password" type="text" class="form-control" required />
                <div v-if="errors.password" class="text-danger">{{ errors.password[0] }}</div>
              </div>

              <!-- Подтверждение пароля -->
              <div class="mb-3">
                <label for="password_confirmation" class="form-label">Подтверждение пароля:</label>
                <input
                    v-model="form.password_confirmation"
                    id="password_confirmation"
                    type="text"
                    class="form-control"
                    required
                />
              </div>

              <button type="submit" class="btn btn-primary w-100">Зарегистрировать</button>

              <!-- сообщения -->
              <div v-if="message" class="alert alert-success mt-3">{{ message }}</div>
              <div v-if="errors.general" class="alert alert-danger mt-3">{{ errors.general[0] }}</div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* стили при необходимости */
</style>
