<template>
    <DialogWidget ref="dialog" title="passwordReset.title" :isTitleTranslated="true" :show-close=true :buttons="buttons" @close="closeDialog" @reset="resetPassword" name="PasswordReset">
        <div class="form-stack">
            <div class="form-field">
                <label for="password-reset-email">{{ $t("passwordReset.email") }}</label>
                <input id="password-reset-email" type="email" v-model="email" required :class="{ 'field-error': emailTouched && !isEmailValid }" />
                <span class="form-hint">{{ $t("passwordReset.emailHint") }}</span>
                <span v-if="emailTouched && !isEmailValid" class="form-error">{{ $t("passwordReset.validation.invalidEmail") }}</span>
            </div>
        </div>
    </DialogWidget>
</template>

<script>
import apiClient from '@/utils/axios.js';
import DialogWidget from '@/components/DialogWidget.vue';
import { showApiError, showSuccess } from '@/utils/feedback.js';

export default {
    name: 'PasswordResetDialog',
    components: {
        DialogWidget,
    },
    data() {
        return {
            email: '',
            emailTouched: false,
            buttons: [{ text: 'passwordReset.reset', action: 'reset', disabled: true }]
        };
    },
    computed: {
        isEmailValid() {
            return /\S+@\S+\.\S+/.test(this.email);
        }
    },
    watch: {
        email() {
            this.emailTouched = true;
            this.buttons[0].disabled = !this.isEmailValid;
        }
    },
    methods: {
        open() {
            this.$refs.dialog.open();
        },
        closeDialog() {
            this.$refs.dialog.close();
        },
        async resetPassword() {
            if (!this.isEmailValid) {
                return;
            }
            try {
                await apiClient.post('/api/users/requestPasswordReset', {
                    email: this.email
                });
                this.$refs.dialog.close();
                showSuccess(this, 'tr:passwordReset.success');
            } catch (error) {
                console.error('Error resetting password:', error);
                showApiError(this, error, 'tr:passwordReset.failure');
            }
        }
    }
};
</script>
