<script lang="ts">
    import {l} from "../util/util.ts";
    import {t} from "astro-i18n";

    let username = "";
    let token = "";

    let error = "";

    async function login() {
        let {tokenStore} = await import("./repo/repo.ts");
        if (username === "" || token === "") {
            token = "";
            error = t("login.error");
            return;
        }
        try {
            let res = await fetch(import.meta.env.PUBLIC_API_SERVER + "/data/me", {
                headers: {
                    "Authorization": "Bearer " + token
                }
            }).then(res => res.json());

            if (res.name !== username) {
                error = t("login.error");
                token = "";
                return;
            }

            tokenStore.set(token);
            window.location.href = l("/dashboard");
        } catch (e) {
            error = t("login.error");
            token = "";
            return;
        }
    }
</script>

<form class="bg-gray-100 dark:bg-neutral-900 p-12 rounded-2xl shadow-2xl border-2 border-gray-600 flex flex-col" on:submit|preventDefault={login}>
    <h1 class="text-4xl text-white text-center">{t("login.title")}</h1>
    <div class="ml-2 flex flex-col">
        <label for="username">{t("login.label.username")}</label>
        <input type="text" id="username" name="username" placeholder={t("login.placeholder.username")} bind:value={username} />
        <label for="token">{t("login.label.token")}</label>
        <input type="password" id="token" name="token" placeholder={t("login.placeholder.token")} bind:value={token} />
    </div>
    <p class="mt-2">
        <a class="text-neutral-500 hover:underline" href={l("/help/token")}>{t("login.generateToken")}</a></p>

    {#if error}
        <p class="mt-2 text-red-500">{error}</p>
    {/if}
    <button class="btn mt-4 !mx-0 justify-center" type="submit" on:click|preventDefault={login}>{t("login.submit")}</button>
</form>

<style lang="postcss">
    input {
        @apply border-2 rounded-md p-2 shadow-2xl w-80
            dark:bg-neutral-800
            focus:outline-none focus:ring-2 focus:ring-neutral-500 focus:border-transparent;
    }

    label {
        @apply text-neutral-300;
    }
</style>