<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';

import VnRow from 'components/ui/VnRow.vue';
import FormPopup from 'src/components/FormPopup.vue';
import VnInput from 'src/components/common/VnInput.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const $props = defineProps({
    id: {
        type: Object,
        default: () => {},
    },
});

const emit = defineEmits(['onSubmit']);

const { t } = useI18n();
const { notify } = useNotify();

const formData = reactive({
    newPassword: null,
    repeatPassword: null,
});

const passRequirements = ref([]);

const setPassword = async () => {
    try {
        if (!formData.newPassword) {
            notify(t('You must enter a new password'), 'negative');
            return;
        }

        if (formData.newPassword != formData.repeatPassword) {
            notify(t(`Passwords don't match`), 'negative');
            return;
        }

        await axios.patch(`Workers/${$props.id}/setPassword`, {
            newPass: formData.newPassword,
        });
        notify(t('Password changed!'), 'positive');
        emit('onSubmit');
    } catch (err) {
        console.error('Error setting password', err);
    }
};

const getPassRequirements = async () => {
    const { data } = await axios.get('UserPasswords/findOne');
    passRequirements.value = data;
};

onMounted(async () => await getPassRequirements());
</script>

<template>
    <FormPopup :title="t('Reset password')" @on-submit="setPassword()">
        <template #form-inputs>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnInput
                    :label="t('New password')"
                    v-model="formData.newPassword"
                    type="password"
                    :required="true"
                    :info="
                        t('passwordRequirements', {
                            length: passRequirements.length,
                            nAlpha: passRequirements.nAlpha,
                            nUpper: passRequirements.nUpper,
                            nDigits: passRequirements.nDigits,
                            nPunct: passRequirements.nPunct,
                        })
                    "
                />
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <VnInput
                    :label="t('Repeat password')"
                    v-model="formData.repeatPassword"
                    type="password"
                />
            </VnRow>
        </template>
    </FormPopup>
</template>

<i18n>
es:
    Reset password: Restablecer contraseña
    New password: Nueva contraseña
    Repeat password: Repetir contraseña
    You must enter a new password: Debes introducir la nueva contraseña
    Passwords don't match: Las contraseñas no coinciden
</i18n>
