<script lang="ts">
    import { goto } from "$app/navigation";
    import { env } from "$env/dynamic/public";
    import UserState, { type UserObj } from "$lib/User.svelte";
    import axios from "axios";

    let oldpassword = $state("");
    let newpassword = $state("");
    let reppassword = $state("");
    let error = $state("");

    async function changePassword() {
        if (newpassword !== reppassword) {
            error = "Passwörter stimmen nicht überein.";
        } else {
            error = "";
        }

        axios
            .post(
                `${env.PUBLIC_JEOPARDY_SERVER_PROTOCOL}://${env.PUBLIC_JEOPARDY_SERVER}/user/changepw`,
                {
                    old: oldpassword,
                    new: newpassword
                },
                { withCredentials: true }
            )
            .then((response) => {
                if (response.status === 200) {
                    goto("/login");
                } else {
                    error = "Passwort ändern fehlgeschlagen";
                }
            })
            .catch((e) => {
                error = "Passwort ändern fehlgeschlagen";
            });
    }
</script>

<div class="flex flex-col gap-4 p-4">
    <div class="flex items-center">
        <h2 class="text-4xl font-bold">Einstellungen</h2>
        <div class="grow"></div>
        <button type="button" class="btn" onclick={() => goto("/")}>Zurück</button>
    </div>
    <div class="rounded-md border-1 p-4">
        <h4 class="font-bold">Passwort ändern</h4>
        <div>
            <label for="oldpassword" class="">Altes Passwort</label>
            <input
                type="password"
                name="oldpassword"
                id="oldpassword"
                class="borders me-4 mt-2 mb-4"
                bind:value={oldpassword}
            />
            <label for="newpassword" class="">Neues Passwort</label>
            <input
                type="password"
                name="newpassword"
                id="newpassword"
                class="borders me-4 mt-2 mb-4"
                bind:value={newpassword}
            />
            <label for="reppassword" class="">Neues Passwort wiederholen</label>
            <input
                type="password"
                name="reppassword"
                id="reppassword"
                class="borders me-4 mt-2 mb-4"
                bind:value={reppassword}
            />
        </div>
        <button type="button" class="btn mb-2 w-fit ps-4 pe-4" onclick={changePassword}
            >Passwort ändern</button
        >
        {#if error.length > 0}
            <div class="text-red-700">{error}</div>
        {/if}
    </div>
</div>

<style>
    .borders {
        border: 1px solid black;
        border-radius: 5px;
        display: flex;
        font-size: larger;
        padding: 2px;
    }
</style>
