<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 { loginSchema } from '$lib/schemas/login';
	import { ZodError } from 'zod';
	import { ClientResponseError } from 'pocketbase';

	let error = '';

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

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

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

	function validateForm() {
		try {
			loginSchema.parse(form);
			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) {
		if (e.data.lenght > 0) {
			const element = Object.keys(e.data.data)[0];
			formErrors[element] = true;
			const dbError = e.data.data[element];
			error = dbError.message;
		} else {
			formErrors.email = true
			formErrors.password = true
			error = e.message;
		}
	}

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

		if (validateForm()) {
			try {
				await pb.collection('users').authWithPassword(form.email, form.password);
				await goto('/');
				window.location.reload();
			} catch (e) {
				console.log(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>Login to your account</Card.Title>
		<Card.Description>Enter your email below to login</Card.Description>
		<Card.Action>
			<Button variant="link" href="/auth/register">Register</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
						id="email"
						type="email"
						placeholder="someone@example.com"
						required
						aria-invalid={formErrors.email}
						bind:value={form.email}
					/>
				</div>
				<div class="grid gap-2">
					<div class="flex items-center">
						<Label for="password">Password</Label>
						<a class="ml-auto inline-block text-sm underline-offset-4 hover:underline">
							Forgot your password?
						</a>
					</div>
					<Input
						id="password"
						type="password"
						required
						bind:value={form.password}
						aria-invalid={formErrors.password}
					/>
				</div>
			</div>
		</form>
	</Card.Content>
	<Card.Footer class="flex-col gap-2">
		<Button type="submit" class="w-full cursor-pointer" onclick={login}>Login</Button>
		<p class="mt-4 text-red-700">{error}</p>
	</Card.Footer>
</Card.Root>
