<script setup>
import { onMounted, ref, watch } from 'vue';
import { useAuthStore } from '@/stores/Auth.js';
import { useRouter } from 'vue-router';
import { generateLogin, generateTemporaryPassword } from '@/services/hooks.js';

const authStore = useAuthStore();
const router = useRouter();

const roles = ref([
    { id: 3, name: 'Региональный менеджер' },
    { id: 4, name: 'Районный менеджер' },
    { id: 5, name: 'Оператор' },
    { id: 6, name: 'Заказчик' },
]);

const form = ref({
    first_name: '',
    middle_name: '',
    last_name: '',
    login: '',
    role_id: null,
    password: '',
    password_confirmation: '',
});

onMounted(() => {
    form.value.password = generateTemporaryPassword();
    form.value.password_confirmation = form.value.password;
});

watch(() => (form.value.login = generateLogin(form.value.first_name, form.value.last_name)));

const message = ref('');
const errors = ref({});

const registration = () => {
    errors.value = {};
    message.value = '';

    authStore.register(form.value).then(({ response, error }) => {
        if (response && (response.status === 201 || response.status === 200)) {
            message.value = response.data.message || 'Регистрация прошла успешно!';

            // Очистка формы
            form.value = {
                first_name: '',
                middle_name: '',
                last_name: '',
                login: '',
                role_id: '',
                password: '',
                password_confirmation: '',
                position: '',
            };
        } else if (error) {
            if (error.response && error.response.data.errors) {
                errors.value = error.response.data.errors;
            } 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="first_name" class="form-label">Имя:</label>
                                <input
                                    v-model="form.first_name"
                                    type="text"
                                    class="form-control"
                                    id="first_name"
                                    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"
                                    type="text"
                                    class="form-control"
                                    id="middle_name"
                                    required
                                />
                                <div v-if="errors.middle_name" class="text-danger">{{ errors.middle_name[0] }}</div>
                            </div>

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

                            <div class="mb-3">
                                <label for="login" class="form-label">Логин:</label>
                                <input
                                    v-model="form.login"
                                    type="text"
                                    class="form-control"
                                    id="login"
                                    required
                                    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" class="form-select" id="role_id" required>
                                    <option value="" disabled>Выберите роль</option>
                                    <option v-for="role in roles" :key="role.id" :value="role.id">
                                        {{ role.name }}
                                    </option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="position" class="form-label">Должность:</label>
                                <input
                                    v-model="form.position"
                                    type="text"
                                    class="form-control"
                                    id="position"
                                    required
                                />
                                <div v-if="errors.login" class="text-danger">{{ errors.login[0] }}</div>
                            </div>
                            <div class="mb-3">
                                <label for="birthday" class="form-label">Дата рождения:</label>
                                <input
                                    v-model="form.birthday"
                                    type="date"
                                    class="form-control"
                                    id="birthday"
                                    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"
                                    type="text"
                                    class="form-control"
                                    id="password"
                                    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"
                                    type="text"
                                    class="form-control"
                                    id="password_confirmation"
                                    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>
