<script lang="ts">
    import { goto } from "$app/navigation";
    import { Button, Checkbox, Input, Alert } from "$lib/components";
    import LL from "$lib/i18n/i18n-svelte";
    import pwKey from "$actions/pwKey";
    import { onMount } from "svelte";
    import { signInPageMessageQueryKey, signInPageTestKeys, type SignInPageMessage } from ".";
    import { AccountService } from "$lib/services/account-service";
    import type { LoginPayload } from "$lib/services/abstractions/IAccountService";
    import { FormError } from "$lib/models/internal/FormError";

    let loading = false;
    let showErrorAlert = false;
    let messageType: SignInPageMessage | undefined = undefined;

    const accountService = new AccountService();

    const formData = {
        username: {
            value: "",
            errors: [],
        },
        password: {
            value: "",
            errors: [],
        },
        persist: {
            value: false,
            errors: [],
        },
        as_payload(): LoginPayload {
            return {
                password: formData.password.value,
                username: formData.username.value,
                persist: !formData.persist.value,
            };
        },
    };

    const formError = new FormError();

    onMount(() => {
        const searcher = new URLSearchParams(window.location.search);
        if (searcher.get(signInPageMessageQueryKey)) {
            messageType = searcher.get(signInPageMessageQueryKey) as SignInPageMessage;
            searcher.delete(signInPageMessageQueryKey);
            history.replaceState(null, "", window.location.origin + window.location.pathname);
        }
    });

    async function submit_form_async() {
        formError.set();
        showErrorAlert = formError.has_error();
        loading = true;
        const loginResponse = await accountService.login_async(formData.as_payload());
        if (loginResponse.isLoggedIn) {
            await goto("/home");
        } else if (loginResponse.knownProblem) {
            formError.set_from_known_problem(loginResponse.knownProblem);
        } else {
            formError.title = $LL.unexpectedError();
            formError.subtitle = $LL.tryAgainSoon();
        }
        loading = false;
        showErrorAlert = formError.has_error();
    }
</script>

<div class="min-h-full flex flex-col justify-center py-12 sm:px-6 lg:px-8">
    {#if messageType}
        <div class="sm:max-w-md sm:mx-auto sm:w-full">
            {#if messageType === "after-password-reset"}
                <Alert
                    title={$LL.signInPage.yourNewPasswordIsApplied()}
                    _pwKey={signInPageTestKeys.afterPasswordResetAlert}
                    message={$LL.signInPage.signInBelow()}
                    closeable
                />
            {:else if messageType === "user-disabled"}
                <Alert
                    title={$LL.signInPage.yourAccountIsDisabled()}
                    _pwKey={signInPageTestKeys.userDisabledAlert}
                    message={$LL.signInPage.contactYourAdminIfDisabled()}
                    closeable
                />
            {:else if messageType === "user-inactivity"}
                <Alert
                    title={$LL.signInPage.youHaveReachedInactivityLimit()}
                    _pwKey={signInPageTestKeys.userInactivityAlert}
                    message={$LL.signInPage.feelFreeToSignInAgain()}
                    closeable
                />
            {/if}
        </div>
    {/if}
    <div class="sm:mx-auto sm:w-full p-2 sm:p-0 sm:max-w-md">
        <h2 class="mt-6 text-3xl tracking-tight font-bold text-gray-900">
            {$LL.signInPage.signIn()}
        </h2>
        <p class="mt-2 text-sm text-gray-600">
            {$LL.or().toLowerCase()}
            <a href="/sign-up" use:pwKey={signInPageTestKeys.signUpAnchor} class="link">
                {$LL.createANewAccount().toLowerCase()}
            </a>
        </p>
    </div>
    <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
            {#if showErrorAlert}
                <Alert title={formError.title} message={formError.subtitle} type="error" _pwKey={signInPageTestKeys.formErrorAlert} />
            {/if}
            <form class="space-y-6 mt-2" use:pwKey={signInPageTestKeys.signInForm} on:submit|preventDefault={submit_form_async}>
                <Input
                    id="username"
                    _pwKey={signInPageTestKeys.usernameInput}
                    name="username"
                    type="email"
                    label={$LL.emailAddress()}
                    required
                    bind:value={formData.username.value}
                />

                <Input
                    id="password"
                    name="password"
                    type="password"
                    label={$LL.password()}
                    _pwKey={signInPageTestKeys.passwordInput}
                    autocomplete="current-password"
                    required
                    bind:value={formData.password.value}
                />

                <div class="flex items-center justify-between">
                    <Checkbox
                        id="remember-me"
                        _pwKey={signInPageTestKeys.rememberMeCheckbox}
                        name="remember-me"
                        bind:checked={formData.persist.value}
                        label={$LL.signInPage.notMyComputer()}
                    />
                    <div class="text-sm">
                        <a href="/reset-password" class="link" use:pwKey={signInPageTestKeys.resetPasswordAnchor}>
                            {$LL.signInPage.resetPassword()}
                        </a>
                    </div>
                </div>

                <Button text={$LL.submit()} fullWidth type="submit" {loading} />
            </form>
        </div>
    </div>
</div>
