<script lang="ts">
	import { Button } from '$lib/components/ui/button/index.js';
	import { Label } from '$lib/components/ui/label/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import * as Card from '$lib/components/ui/card/index.js';
	import { pb } from '$lib/db.svelte';
	import { goto } from '$app/navigation';
	import { registerSchema } from '$lib/schemas/register';
	import { ZodError } from 'zod';
	import { ClientResponseError } from 'pocketbase';

	let error = '';

	const form = {
		email: '',
		name: '',
		password: '',
		passwordConfirm: ''
	};

	interface FormErrors {
		email: boolean;
		name: boolean;
		password: boolean;
		passwordConfirm: boolean;
		[key: string]: boolean;
	}

	const formErrors = {
		email: false,
		name: false,
		password: false,
		passwordConfirm: false
	} as FormErrors;

	function validateForm() {
		try {
			registerSchema.parse(form);
			if (form.password !== form.passwordConfirm) {
				formErrors.password = true;
				formErrors.passwordConfirm = true;
				error = "Passwords don't match";
				return false;
			}
			return true;
		} catch (e) {
			if (e instanceof ZodError) {
				error = e.issues[0].message;
				formErrors[e.issues[0].path[0] as string] = true;
				return false;
			}
		}
	}

	function handleDBErrors(e: ClientResponseError) {
		const element = Object.keys(e.data.data)[0];
		formErrors[element] = true;
		const dbError = e.data.data[element];
		if (dbError.code === 'validation_not_unique') {
			error = `This ${element} is already used by someone. Maybe try logging in if it's you.`;
		} else error = dbError.message;
	}

	async function register() {
		// reset all errors
		error = '';
		Object.keys(formErrors).forEach((i) => {
			formErrors[i] = false;
		});

		if (validateForm()) {
			try {
				await pb.collection('users').create(form);

				await pb.collection('users').authWithPassword(form.email, form.password);
				await goto('/');
				window.location.reload();
			} catch (e) {
				if (e instanceof ClientResponseError) {
					handleDBErrors(e);
				}
			}
		}
	}
</script>

<Card.Root class="absolute top-[50%] left-[50%] w-full max-w-sm translate-[-50%]">
	<Card.Header>
		<Card.Title>Register to heddit</Card.Title>
		<Card.Description>Enter your email below to register</Card.Description>
		<Card.Action>
			<Button variant="link" href="/auth/login">Login</Button>
		</Card.Action>
	</Card.Header>
	<Card.Content>
		<form>
			<div class="flex flex-col gap-6">
				<div class="grid gap-2">
					<Label for="email">Email</Label>
					<Input
						aria-invalid={formErrors.email}
						id="email"
						type="email"
						placeholder="someone@example.com"
						required
						bind:value={form.email}
					/>
				</div>
				<div class="grid gap-2">
					<Label for="name">Username</Label>
					<Input
						aria-invalid={formErrors.name}
						id="name"
						type="text"
						placeholder="Someone"
						required
						bind:value={form.name}
					/>
				</div>
				<div class="grid gap-2">
					<div class="flex items-center">
						<Label for="password">Password</Label>
					</div>
					<Input
						aria-invalid={formErrors.password}
						id="password"
						type="password"
						required
						bind:value={form.password}
					/>
				</div>
				<div class="grid gap-2">
					<div class="flex items-center">
						<Label for="passwordConfirm">Confirm your password</Label>
					</div>
					<Input
						aria-invalid={formErrors.passwordConfirm}
						id="passwordConfirm"
						type="password"
						required
						bind:value={form.passwordConfirm}
					/>
				</div>
			</div>
		</form>
	</Card.Content>
	<Card.Footer class="flex-col gap-2">
		<Button type="submit" class="w-full cursor-pointer" onclick={register}>Register</Button>
		<p class="mt-4 text-red-700">{error}</p>
	</Card.Footer>
</Card.Root>
