<template>
  <div class="content-l">
    <h2>Add User</h2>
    <UiError :error="error" @close="error = undefined"></UiError>
    <div class="col-2 tile-l">
        <UiInput label="First Name">
            <input type="text" v-model="user.firstname">
        </UiInput>
        <UiInput label="Last Name">
            <input type="text" v-model="user.lastname">
        </UiInput>
    </div>
    <div class="col-2 tile-l">
        <UiInput label="Username" required>
            <input type="text" v-model="user.username">
        </UiInput>
        <UiInput label="E-Mail" required>
            <input type="text" v-model="user.email">
        </UiInput>
    </div>
    <div class="col-2 tile-l">
        <UiInput label="Role" required>
            <select v-model="user.role">
                <option value="USER">User</option>
                <option value="ADMIN">Admin</option>
            </select>
        </UiInput>
        <UiInput label="Password" required>
            <input type="password" v-model="user.password">
        </UiInput>
    </div>
    <div class="center">
        <UiButton class="width-6rem" @click="() => useRouter().push('/account/settings/users')">Zurück</UiButton>
        <UiButton class="width-6rem" @click="() => create()">Add</UiButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { User, UserCreation } from '~/classes/User';
import UiError from '~/components/ui/UiError.vue';

const user = ref(new UserCreation());

const error: Ref<string | undefined> = ref(undefined);
function create()
{
    const _user = user.value;
    if (_user.email && _user.username && _user.role && _user.password)
    {   
        User.create(user.value, () => {
            useRouter().push('/account/settings/users');
        });
    }
    else 
    {
        error.value = "Please fill out all required fields.";
        throw new Error("Invalid user object.");
    }
}
</script>

<style scoped>

</style>