<script>
	import {onMount} from "svelte";
	import {link, querystring} from "svelte-spa-router";
	import {api_base, projects_base, IconNames} from "$shared/lib/configuration";
	import Button from "$shared/components/button.svelte";
	import Alert from "$shared/components/alert.svelte";
	import {login} from "$shared/lib/api/user";
	import {is_email} from "$shared/lib/helpers";
	import Layout from "./_layout.svelte";

	const loginForm = {
		loading: false,
		values: {
			username: "",
			password: "",
		},
		alert: {
			title: "",
			type: "",
			message: "",
			isVisible: false,
			show(type, obj) {
				loginForm.alert.title = obj.title;
				loginForm.alert.message = obj.text;
				loginForm.alert.type = type;
				loginForm.alert.isVisible = true;
				loginForm.loading = false;
			},
			hide() {
				loginForm.alert.isVisible = false;
				loginForm.alert.title = "";
				loginForm.alert.message = "";
				loginForm.alert.type = "";
			},
		},
		is_valid() {
			return is_email(loginForm.values.username) && loginForm.values.password.length > 0;
		},
		async submit_form() {
			if (loginForm.loading) {
				return;
			}
			if (loginForm.is_valid()) {
				loginForm.alert.hide();
				loginForm.loading = true;
				try {
					const response = await login(loginForm.values);
					if (response.ok) {
						location.replace(projects_base("#/home"));
					} else {
						if (response.data.title || response.data.text) {
							loginForm.alert.show("error", {
								title: response.data.title ?? "",
								text: response.data.text ?? "",
							});
						} else {
							loginForm.alert.show("error", {
								title: "An unknown error occured",
								text: "Try again soon",
							});
						}
					}
				} catch (e) {
					console.error(e);
					loginForm.alert.show("error", {
						title: "An error occured",
						text: "Could not connect to server, please check your internet connection",
					});
				}
			} else {
				loginForm.alert.show("error", {
					title: "Invalid form",
				});
			}
		},
	};

	onMount(() => {
		if ($querystring === "deleted") {
			loginForm.alert.show("info", {
				title: "Account deleted",
				text: "Your account and all its data was successfully deleted.",
			});
		}
		if ($querystring === "expired") {
			loginForm.alert.show("info", {
				title: "Session expired",
				text: "Your session has expired, feel free to log in again.",
			});
		}
	});
</script>

<Layout>
    <form on:submit|preventDefault={loginForm.submit_form}
          class="margin-bottom-md max-width-xxs">
        <fieldset>
            <legend class="form-legend">
                <span class="margin-bottom-xs">Log into your account</span>
                <br/>
                <span class="text-sm">... or <a href="/signup"
                                                use:link>create a new one</a></span>
            </legend>
            <div class="margin-bottom-xxs max-width-xxs">
                <Alert visible={loginForm.alert.isVisible}
                       title={loginForm.alert.title}
                       message={loginForm.alert.message}
                       type={loginForm.alert.type}/>
            </div>
            <div class="margin-bottom-xxs">
                <input type="email"
                       placeholder="Email address"
                       class="form-control width-100%"
                       id="username"
                       bind:value={loginForm.values.username}/>
            </div>
            <div class="margin-bottom-xxs">
                <input type="password"
                       placeholder="Password"
                       id="password"
                       class="form-control width-100%"
                       bind:value={loginForm.values.password}/>
                <div class="flex justify-end">
                    <a tabindex="-1"
                       class="text-sm"
                       href="/forgot"
                       use:link>Reset password</a>
                </div>
            </div>
            <div class="flex justify-between">
                <Button text="Login with Github"
                        variant="secondary"
                        icon="{IconNames.github}"
                        icon_right_aligned="true"
                        href={api_base("_/account/create-github-session")}
                        loading={loginForm.loading}
                />
                <Button text="Login"
                        type="submit"
                        variant="primary"
                        loading={loginForm.loading}/>
            </div>
        </fieldset>
    </form>
</Layout>
