<script lang="ts">
	import { goto } from '$app/navigation';
	import { userStore } from '$lib/UserStore.svelte';
	import { post, preventDefault } from '$lib/utils';
	import { onMount } from 'svelte';

	onMount(() => {
		if (userStore.isLoggedIn) {
			goto('/');
		}
	});

	let userData = $state({
		email: '',
		password: ''
	});

	async function register() {
		console.log('this is a requeset');
		try {
			const r = await post('user/login', userData);
			userStore.user = r;
			goto('/');
		} catch (e) {
			// TODO messages
			console.log(e);
			return;
		}

		userData = {
			email: '',
			password: ''
		};
	}
</script>

<div class="w-full h-lvh flex justify-center items-center">
	<form class="card p-3 min-w-[300px]" onsubmit={preventDefault(register)}>
		<h1 class="text-center">Login</h1>
		<fieldset class="py-2">
			<label class="flabel" for="email">Email</label>
			<input required class="finput" id="email" type="email" bind:value={userData.email} />
		</fieldset>
		<fieldset class="py-2">
			<label class="flabel" for="password">Password</label>
			<input required class="finput" id="password" type="password" bind:value={userData.password} />
		</fieldset>
		<div class="btns">
			<button type="submit" class="btn-confirm"> Login </button>
		</div>
		<div class="btns">
			<button class="text-secudanry" type="button" onclick={() => goto('/register')}>
				Register
			</button>
		</div>
	</form>
</div>
