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

	export let user: BenutzerClient | null;

	let email: string;
	let passwort: string;

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

		if (response === null) {
			errorHidden = false;
		} else {
			window.location.href = "/dashboard";
		}
	}

	let errorHidden = true;
</script>

<div
	id="card-login"
	class="rounded-none lg:rounded-lg lg:card lg:box lg:ring-2 border-t-2 lg:border-none border-gray-500/50 ring-gray-500/50 xs:px-2 md:px-4 py-2"
>
	{#if !user}
	<form on:submit={login}>
		<div class="grid grid-cols-[1fr] xs:grid-cols-[2fr_2fr_1fr] gap-2">
			<input
				class="my-1 rounded-md px-2 py-1 w-full"
				type="text"
				placeholder="nutzer@email.com"
				autocomplete="off"
				name="email"
				bind:value={email}
				on:focus={() => (errorHidden = true)}
				required
			/>
			<input
				class="my-1 rounded-md px-2 py-1 w-full"
				type="password"
				minlength="8"
				placeholder="********"
				autocomplete="off"
				name="passwort"
				bind:value={passwort}
				on:focus={() => (errorHidden = true)}
				required
			/>
			{#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 id="LoginButton" class="button self-center" type="submit">login</button>
		</div>

		<div
			id="passwort-vergessen"
			class="grid grid-cols-1 lg:grid-cols-[3fr_2fr] gap-2"
		>
			<div class="w-full text-left self-center">
				<a
					class="justify-self-start text-sm font-bold no-underline hover:text-primary"
					href="/auth/signup">Registrieren</a
				>
				/
				<a
					class="justify-self-start text-sm font-bold no-underline hover:text-primary"
					href="/auth/passwort-vergessen">Passwort vergessen</a
				>
			</div>
		</div>
	</form>
	{:else}
		<div class="flex flex-row gap-4 items-center">
			<img src={user.profilbild || "/images/profile-placeholder.png"} class="w-14 h-14 rounded-full border">
			<div class="flex flex-col">
				<span class="text-base font-bold">{user.vorname} {user.name}</span>
				<span class="text-black text-opacity-50">{user.email}</span>
				<div class="flex flex-row gap-4">
					<a href="/dashboard" class="text-sm">Dashboard</a>
					<a href="/auth/logout" class="text-sm">Ausloggen</a>
				</div>
			</div>
		</div>
	{/if}
</div>

<style lang="postcss">
</style>
