<script lang="ts">
	import { addNotification } from "@ibcornelsen/ui";
	import { api } from "astro-typesafe-api/client";

	export let navigate: (target: string) => void;
	export let onRegister: (response: { email: string, name: string, vorname: string }) => void;
	export let password: string;
	export let email: string;
	let vorname: string;
	let name: string;

	async function signUp(e: SubmitEvent) {
		e.preventDefault()
		try {
			const response = await api.user.PUT.fetch({
				email,
				passwort: password,
				vorname,
				name,
			});

			onRegister({
				email,
				name,
				vorname
			})
		} catch (e) {
			addNotification({
				message: "Ups...",
				subtext:
					"Da ist wohl etwas schiefgelaufen. Diese Email Adresse ist bereits in Benutzung, haben sie vielleicht bereits ein Konto bei uns?",
				type: "error",
				timeout: 0,
				dismissable: true,
			});
		}
	}
</script>

<form style="width:50%;margin: 0 auto" name="signup" on:submit={signUp}>
	<h1>Registrieren</h1>
	<div class="flex flex-col gap-4">
		<div class="flex flex-row gap-4 w-full">
			<div class="w-1/2">
				<h4>Vorname</h4>
				<input
					type="text"
					placeholder="Vorname"
					name="vorname"
					class="px-2.5 py-1.5 rounded-lg border bg-gray-50"
					bind:value={vorname}
					required
				/>
			</div>
			<div class="w-1/2">
				<h4>Nachname</h4>
				<input
					type="text"
					placeholder="Nachname"
					name="nachname"
					class="px-2.5 py-1.5 rounded-lg border bg-gray-50"
					bind:value={name}
					required
				/>
			</div>
		</div>
		<div>
			<h4>Email</h4>
			<input
				type="email"
				placeholder="Email"
				name="email"
				class="px-2.5 py-1.5 rounded-lg border bg-gray-50"
				bind:value={email}
				required
			/>
		</div>
		<div>
			<h4>Passwort</h4>
			<input
				type="password"
				placeholder="********"
				name="passwort"
				class="px-2.5 py-1.5 rounded-lg border bg-gray-50"
				bind:value={password}
				required
			/>
		</div>
		<button class="button" type="submit">Registrieren</button>
		<div class="flex-row justify-between" style="margin-top: 10px">
			<button on:click={() => navigate("login")}>Einloggen</button>
			<a href="/user/passwort_vergessen">Passwort Vergessen?</a>
		</div>
	</div>
</form>
