<script lang="ts">
    import {t} from "$lib/i18n";
    import {API_ROOT} from "$lib/config";
    import {fetch_timeout} from "$lib/util";
    import {Logger, logSetup} from "../../../lib/logger";
    import {onMount} from "svelte";
    import {enforce_session} from "$lib/auth";

    let email = "";
    let isloading = false;
    let isFinished = false;
    let hasError = false;
    let error = "";

    logSetup();
    let logger = new Logger("login/+page.svelte");

    async function generateMagicLink() {
        if (isloading) {
            return;
        }
        isloading = true;


        try {
            let resp = await fetch_timeout(`${API_ROOT}/v1/auth/magic-link`, {
                'method': 'POST',
                'headers': {
                    'Content-Type': 'application/json'
                },
                'body': JSON.stringify({
                    email: email
                })
            });
            if (!resp.ok) {
                hasError = true;
                const rawerror = JSON.parse(await resp.text()).errors[0].message;

                error = t(`login.apierror.${rawerror}`);

                isloading = false;
            } else {
                isloading = false;
                isFinished = true;
            }
        } catch (e) {
            hasError = true;
            logger.error(`Error requesting magic link from api: ${e}`);
            error = t(`login.apierror.${e.name}`);
            isloading = false;
        }
    }

    onMount(async () => {
        let st_result = await enforce_session();
        if (st_result[0]) {
            // User already authed, redirect them
            logger.info("User already logged in");
            window.location.href = "/admin";
            return;
        }
    })
</script>

<div class="flex in-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="w-full max-w-md">
        {#if !isFinished}
            <!-- Title -->
            <div>
                <h1 class="font-semibold text-2xl">{t('login.title')}</h1>
                <h2 class="ftext-sm">{t('login.subtitle')}</h2>
            </div>

            <!-- The actual form -->
            <form class="mt-5" action="#" method="POST" on:submit|preventDefault={generateMagicLink}>
                <div class="rounded-md shadow-sm">
                    <label for="email">{t('login.prompt')}</label>
                    <input bind:value={email} id="email"
                           class="dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                    {#if hasError}
                        <span class="text-red-600 text-sm">{error}</span>
                    {/if}
                </div>

                <button class="bg-purple-400 dark:bg-purple-600 mt-4 w-full py-2 -space-y-px rounded-md shadow-sm place-content-center">
                    {#if !isloading}
                        {t('login.actionButtonText')}
                    {:else}
                        <svg class="animate-spin w-5 h-5 inline-block m-auto" xmlns="http://www.w3.org/2000/svg"
                             fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                    stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor"
                                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    {/if}
                </button>

                <div class="text-xs mt-0.5">
                    <a class="font-bold text-purple-400 dark:text-purple-600" href="/signup">{t('login.createaccount')}</a>
                </div>
            </form>
        {:else}
            <!-- Title -->
            <div>
                <h1 class="font-semibold text-2xl">{t('login.sentMagicLink')}</h1>
                <h2 class="ftext-sm">{t('login.magicLinkExplainer')}</h2>
            </div>
        {/if}
    </div>
</div>