<script setup>
import AppLayout from '../../../../resources/js/layouts/AppLayout.vue'
import {computed, onMounted, reactive, ref} from 'vue'
import { toast } from 'vue3-toastify'
import ShadowedBox from "../../../Views/Components/ShadowedBox.vue";
import {useAjax} from "../../../../resources/js/components/ajaxHandler.js";
import ErrorText from "../../../Views/Components/ErrorText.vue";


const props = defineProps({
    navbar: Object,
    tenant: String,
    user: Object,
    currentPath: String,
    errors: Object,
    availableLocalGroups: Array,
})

onMounted(() => {
    if (undefined !== props.errors && undefined !== props.errors.username) {
        toast.error(props.errors.username[0])
    }
})
const form = reactive({
    email: '',
    verificationToken: '',
})

const errors = reactive({})
const { request } = useAjax()

const isValid = computed(() => {
    errors.email = ''

    if (!form.email) {
        errors.email = 'Bitte gib deine E-Mail-Adresse ein'
    }


    return !errors.email
})

async function submit() {

    if (!isValid.value) return false

    const data = await request("/api/v1/reset-password", {
        method: "POST",
        body: {
            "email": form.email,
        }
    });

    if (data.error_types) {
        Object.keys(data.error_types).forEach((key) => {
            if (key in errors) {
                errors[key] = data.error_types[key]
            }
        });

    } else {
        window.location.href = '/register/verifyEmail';
        toast.success(data.message)
    }
    return;
}


const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
</script>

<template>
    <AppLayout title='Passwort zurücksetzen' :user="props.user" :navbar="props.navbar" :tenant="props.tenant" :currentPath="props.currentPath">
        <form method="POST" action="/reset-password" @submit.prevent="submit">
            <input type="hidden" name="_token" :value="csrfToken" />
            <shadowed-box style="width: 75%; margin: 150px auto; padding: 20px;">
                <table>
                    <tr>
                        <th>E-Mail-Adresse</th>
                        <td>
                            <input type="email" name="email" id="email" v-model="form.email" />
                            <ErrorText :message="errors.email" />
                        </td>
                    </tr>

                    <tr>
                        <td colspan="2">
                            <input type="submit" value="Verifizierung starten" style="margin-top: 20px;" />
                        </td>
                    </tr>
                </table>
            </shadowed-box>
        </form>
    </AppLayout>
</template>

<style>
    th {
        width: 150px;
    }

</style>
