<script lang="ts">
	import { loginClient } from "#lib/login.js";
	import CrossCircled from "radix-svelte-icons/src/lib/icons/CrossCircled.svelte";
	import { fade } from "svelte/transition";

	let email: string;
	let passwort: string;

	export let redirect: string | null = null;

	async function login(e: SubmitEvent) {
		e.preventDefault();
		const response = await loginClient(email, passwort);

		if (response === null) {
			errorHidden = false;
		} else {
			if (redirect) {
				window.location.href = redirect;
				return;
			}

			window.location.href = "/dashboard";
		}
	}

	let errorHidden = true;
</script>

<div class="mx-auto w-1/3 bg-base-200 p-8 border border-base-300 rounded-lg">
	<h1 class="text-3xl mb-4">Login</h1>
	<form class="flex flex-col gap-4" on:submit={login}>
		<div class="flex flex-col gap-2">
			<h4 class="text-base">Email</h4>
			<input
				class="input input-bordered text-base text-base-content font-medium"
				type="text"
				placeholder="nutzer@email.com"
				name="email"
				bind:value={email}
				on:focus={() => (errorHidden = true)}
				required
			/>
		</div>
		<div class="flex flex-col gap-2">
			<h4>Passwort</h4>
			<input
				class="input input-bordered text-base text-base-content font-medium"
				type="password"
				minlength="8"
				placeholder="********"
				name="passwort"
				bind:value={passwort}
				on:focus={() => (errorHidden = true)}
				required
			/>
		</div>
		{#if !errorHidden}
		<div role="alert" class="alert alert-error" in:fade out:fade={{delay: 400}}>
			<CrossCircled size={24} />
			<span class="font-semibold">Das hat leider nicht geklappt, haben sie ihr Passwort und ihre Email Adresse richtig eingegeben?</span>
		</div>
		{/if}
			<button class="button" type="submit">Einloggen</button>
		<div class="flex-row justify-between" style="margin-top: 10px">
			<a class="link link-hover" href="/auth/signup{redirect ? `?redirect=${redirect}` : ""}">Registrieren</a>
			<a class="link link-hover" href="/auth/passwort-vergessen{redirect ? `?redirect=${redirect}` : ""}"
				>Passwort Vergessen?</a
			>
		</div>
	</form>
</div>
