<template>
    <DialogWidget ref="dialog" title="register.title" :show-close="true" :buttons="buttons" :modal="true"
        @close="closeDialog" @register="register" width="35em" height="33em" name="RegisterDialog"
        :isTitleTranslated="true">
        <div class="form-content">
            <div>
                <label>{{ $t("register.email") }}<input type="email" v-model="email" /></label>
            </div>
            <div>
                <label>{{ $t("register.username") }}<input type="text" v-model="username" /></label>
            </div>
            <div>
                <label>{{ $t("register.password") }}<input type="password" v-model="password" /></label>
            </div>
            <div>
                <label>{{ $t("register.repeatPassword") }}<input type="password" v-model="repeatPassword" /></label>
            </div>
            <SelectDropdownWidget labelTr="settings.personal.label.language" :v-model="language"
                tooltipTr="settings.personal.tooltip.language" :list="languages" :value="language" />
        </div>
    </DialogWidget>
</template>

<script>
import { mapActions } from 'vuex';
import apiClient from '@/utils/axios.js';
import DialogWidget from '@/components/DialogWidget.vue';
import SelectDropdownWidget from '@/components/form/SelectDropdownWidget.vue';

export default {
    name: 'RegisterDialog',
    components: {
        DialogWidget,
        SelectDropdownWidget,
    },
    data() {
        return {
            email: '',
            username: '',
            password: '',
            repeatPassword: '',
            language: null,
            languages: [],
            buttons: [
                { text: 'register.close', action: 'close' },
                { text: 'register.register', action: 'register', disabled: !this.canRegister }
            ]
        };
    },
    computed: {
        canRegister() {
            return this.password && this.repeatPassword && this.password === this.repeatPassword;
        }
    },
    watch: {
        canRegister(newValue) {
            this.buttons[1].disabled = !newValue;
        }
    },
    async created() {
        await this.getLanguages();
        await this.getBrowserLanguage();
    },
    methods: {
        ...mapActions(['login']),
        async getBrowserLanguage() {
            const browserLanguage = navigator.language || navigator.languages[0];
            let short = '';
            if (browserLanguage.startsWith('de')) {
                short = 'de';
            } else {
                short = 'en';
            }
            const response = await apiClient.post('/api/settings/getparamvalueid', { paramValue: short });
            this.language = response.data.paramValueId;
        },
        open() {
            this.$refs.dialog.open();
        },
        closeDialog() {
            this.$refs.dialog.close();
        },
        async register() {
            if (!this.canRegister) {
                this.$root.$refs.errrorDialog.open('tr:register.passwordMismatch');
                return;
            }

            try {
                const response = await apiClient.post('/api/auth/register', {
                    email: this.email,
                    username: this.username,
                    password: this.password,
                    language: this.language
                });

                if (response.status === 201) {
                    this.login(response.data);
                    this.$refs.dialog.close();
                    this.$router.push('/activate');
                } else {
                    this.$root.$refs.errrorDialog.open("tr:register.failure");
                }
            } catch (error) {
                if (error.response && error.response.status === 409) {
                    this.$root.$refs.errrorDialog.open('tr:register.' + error.response.data.error);
                } else {
                    console.error('Error registering user:', error);
                    this.$root.$refs.errrorDialog.open('tr:register.' + error.response.data.error);
                }
            }
        },
        async getLanguages() {
            try {
                const response = await apiClient.post('/api/settings/getparamvalues', {
                    type: 'language'
                });
                this.languages = response.data.map(item => { return { value: item.id, captionTr: `settings.personal.language.${item.name}` } });
            } catch (err) {
                console.error('Error loading languages:', err);
            }
        }
    }
};
</script>

<style scoped>
.form-content>div {
    margin-bottom: 1em;
}

label {
    display: block;
    margin-bottom: 0.5em;
}

input[type="email"],
input[type="text"],
input[type="password"],
select {
    width: 100%;
    padding: 0.5em;
    box-sizing: border-box;
}
</style>
