<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import { pb, type ClientResponseError } from "$lib";
	import { Button } from "$lib/components/ui/button";
	import * as Field from "$lib/components/ui/field";
	import { Input } from "$lib/components/ui/input";
	import { Spinner } from "$lib/components/ui/spinner";
	import CloseCircleLine from "remixicon-svelte/icons/close-circle-line";
	import { toast } from "svelte-sonner";

	let email = $state("");
	let password = $state("");
	let loggingIn = $state(false);

	async function tryLogin() {
		loggingIn = true;
		try {
			await pb.collection("users").authWithPassword(email, password);
			await goto(resolve("/"));
		} catch (_err) {
			const err = _err as ClientResponseError;
			console.error("Login error:", err);
			toast.error(err.message ?? "An error occurred while logging in.", {
				icon: CloseCircleLine
			});
		} finally {
			loggingIn = false;
		}
	}
</script>

<div class="flex h-screen w-screen items-center justify-center">
	<form
		class="w-screen p-4 md:w-3xl"
		onsubmit={(e) => {
			e.preventDefault();
			tryLogin();
		}}
	>
		<Field.Set>
			<Field.Group>
				<Field.Field>
					<h2 class="mb-2 text-2xl">CCTV Login</h2>
					<Field.Label for="email">Email</Field.Label>
					<Input
						id="email"
						type="email"
						placeholder="Enter your email"
						required
						disabled={loggingIn}
						bind:value={email}
					/>
				</Field.Field>
				<Field.Field>
					<Field.Label for="password">Password</Field.Label>
					<Input
						id="password"
						type="password"
						placeholder="Enter your password"
						required
						disabled={loggingIn}
						bind:value={password}
					/>
				</Field.Field>
				<Button type="submit" disabled={loggingIn}>
					{#if loggingIn}
						<Spinner />
					{/if}
					Login
				</Button>
			</Field.Group>
		</Field.Set>
	</form>
</div>
