<script lang="ts">
	import InputWithLabel from '../../components/forms/InputWithLabel.svelte';
	import { getContext, onMount } from 'svelte';
	import { goto } from '$app/navigation';
	let errors = { username_error: null, password_error: null };
	let username = '';
	let password = '';

	const { login, isAuth, initialLoading } = getContext('auth');

	$: {
		!$initialLoading && !!$isAuth && goto('/dashboard');
	}
	let loading = false
</script>

<div class="parent">
	<div>
		<h1>Se connecter</h1>
		<InputWithLabel
			change={() => {
				errors.username_error = null;
			}}
			type="text"
			bind:value={username}
			label="Nom d'utilisateur"
			errors={errors.username_error != null ? [errors.username_error] : []}
		/>
		<InputWithLabel
			change={() => {
				errors.password_error = null;
			}}
			type="password"
			bind:value={password}
			label="Mot de passe"
			errors={errors.password_error != null ? [errors.password_error] : []}
		/>
		<button
			class="primary-btn"
			on:click={() => {
				loading = true;
				login(username, password).then(()=>{loading=false}).catch((r) => {
					errors = { ...errors, ...r.data.detail };
					loading = false;
				});
			}}

		>
			{#if loading}
				<span class="spinner" />
			{:else}
				Se connecter
			{/if}
		</button>
	</div>
</div>

<style lang="scss">
	h1 {
		font-size: 4em;
	}
	.parent {
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 50px;
		div {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 20px;

			width: min(100%, 666px);
			padding: 7px 20px;
		}
	}
	.spinner{
		width: 15px;
		height: 15px;
		border-width: 2px!important;
	}
</style>
