<script setup>
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import FetchData from 'components/FetchData.vue';
import VnInput from 'src/components/common/VnInput.vue';

const { t } = useI18n();
const router = useRouter();

const newAccountForm = reactive({
    active: true,
});
const rolesOptions = ref([]);
const redirectToAccountBasicData = (_, { id }) => {
    router.push({ name: 'AccountBasicData', params: { id } });
};
</script>

<template>
    <FetchData
        url="VnRoles"
        :filter="{ fields: ['id', 'name'], order: 'name ASC' }"
        @on-fetch="(data) => (rolesOptions = data)"
        auto-load
    />
    <FormModelPopup
        :title="t('account.card.newUser')"
        url-create="VnUsers"
        model="users"
        :form-initial-data="newAccountForm"
        @on-data-saved="redirectToAccountBasicData"
    >
        <template #form-inputs="{ data, validate }">
            <div class="column q-gutter-sm">
                <VnInput
                    v-model="data.name"
                    :label="t('account.create.name')"
                    :rules="validate('VnUser.name')"
                />
                <VnInput
                    v-model="data.nickname"
                    :label="t('account.create.nickname')"
                    :rules="validate('VnUser.nickname')"
                />
                <VnInput
                    v-model="data.email"
                    :label="t('account.create.email')"
                    type="email"
                    :rules="validate('VnUser.email')"
                />
                <VnSelect
                    :label="t('account.create.role')"
                    v-model="data.roleFk"
                    :options="rolesOptions"
                    option-value="id"
                    option-label="name"
                    map-options
                    hide-selected
                    :rules="validate('VnUser.roleFk')"
                />
                <VnInput
                    v-model="data.password"
                    :label="t('account.create.password')"
                    type="password"
                    :rules="validate('VnUser.password')"
                />
                <QCheckbox
                    :label="t('account.create.active')"
                    v-model="data.active"
                    :toggle-indeterminate="false"
                    :rules="validate('VnUser.active')"
                />
            </div>
        </template>
    </FormModelPopup>
</template>
