<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import axios from 'axios';
import FormModel from 'components/FormModel.vue';
import VnChangePassword from 'src/components/common/VnChangePassword.vue';

const { t } = useI18n();
const route = useRoute();
const canChangePassword = ref(0);

const filter = computed(() => {
    return {
        fields: ['active', 'email', 'name'],
        where: { id: route.params.id },
    };
});

async function hasCustomerRole() {
    const { data } = await axios(`Clients/${route.params.id}/hasCustomerRole`);
    canChangePassword.value = data;
}
</script>
<template>
    <FormModel
        :url-update="`Clients/${route.params.id}/updateUser`"
        :filter="filter"
        model="customer"
        :mapper="
            ({ account }) => {
                const { name, email, active } = account;
                return {
                    active,
                    name,
                    email,
                };
            }
        "
        @on-fetch="hasCustomerRole()"
        auto-load
    >
        <template #form="{ data, validate }">
            <QCheckbox :label="t('Enable web access')" v-model="data.account.active" />
            <VnInput :label="t('User')" clearable v-model="data.account.name" />
            <VnInput
                :label="t('Recovery email')"
                :rules="validate('client.email')"
                clearable
                type="email"
                v-model="data.account.email"
                class="q-mt-sm"
                :info="t('This email is used for user to regain access their account')"
            />
        </template>
        <template #moreActions>
            <QBtn
                :label="t('globals.changePass')"
                color="primary"
                icon="edit"
                :disable="!canChangePassword"
                @click="$refs.changePassRef.show"
            />
        </template>
    </FormModel>
    <VnChangePassword
        ref="changePassRef"
        :submit-fn="
            async (newPass) => {
                await axios.patch(`Clients/${$route.params.id}/setPassword`, {
                    newPassword: newPass,
                });
            }
        "
    />
</template>
<i18n>
es:
    Enable web access: Habilitar acceso web
    User: Usuario
    Recovery email: Correo de recuperacion
    This email is used for user to regain access their account: Este correo electrónico se usa para que el usuario recupere el acceso a su cuenta
</i18n>
