<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 ButtonGroup from "$lib/components/ui/button-group";
	import * as Drawer from "$lib/components/ui/drawer";
	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 name = $state("");
	let host = $state("");
	let port = $state("");
	let username = $state("");
	let password = $state("");
	let adding = $state(false);

	let portEl = $state<HTMLInputElement | null>(null);

	function onHostInput(e: Event) {
		const el = e.currentTarget as HTMLInputElement;
		const value = el.value;
		const separatorIndex = value.lastIndexOf(":");

		if (separatorIndex === -1) return;

		host = value.slice(0, separatorIndex);
		const rawPort = value.slice(separatorIndex + 1);
		if (rawPort.length > 0) port = rawPort.replace(/\D/g, "").slice(0, 5);

		requestAnimationFrame(() => {
			portEl?.focus();
		});
	}

	async function tryAddCamera() {
		adding = true;
		try {
			const camera = await pb.collection("cameras").create({
				name,
				onvif_host: `${host}:${port}`,
				username,
				password
			});
			await goto(resolve(`/cam/${camera.id}`));
		} catch (_err) {
			const err = _err as ClientResponseError;
			console.error("Add camera error:", err);
			toast.error(err.message ?? "An error occurred while adding the camera.", {
				icon: CloseCircleLine
			});
		} finally {
			adding = false;
		}
	}
</script>

<Drawer.Root
	bind:open={
		() => true,
		(v) => {
			if (!v) goto(resolve("/"));
		}
	}
>
	<Drawer.Content>
		<div class="mx-auto w-full max-w-sm overflow-y-auto p-1">
			<Drawer.Header>
				<Drawer.Title class="text-xl">New Camera</Drawer.Title>
			</Drawer.Header>
			<form
				onsubmit={(e) => {
					e.preventDefault();
					tryAddCamera();
				}}
			>
				<Field.Set>
					<Field.Group>
						<Field.Field>
							<Field.Label for="name">Camera Name</Field.Label>
							<Input id="name" placeholder="My Camera" bind:value={name} disabled={adding} />
						</Field.Field>
						<Field.Field>
							<Field.Label for="host">Camera URL</Field.Label>
							<ButtonGroup.Root>
								<ButtonGroup.Text>onvif://</ButtonGroup.Text>
								<Input
									id="host"
									bind:value={host}
									oninput={onHostInput}
									placeholder="IP Address"
									disabled={adding}
								/>
								<ButtonGroup.Separator />
								<ButtonGroup.Text>:</ButtonGroup.Text>
								<Input
									id="port"
									bind:ref={portEl}
									bind:value={port}
									type="number"
									min={1}
									max={65535}
									class="min-w-22! flex-0!"
									placeholder="Port"
									disabled={adding}
								/>
							</ButtonGroup.Root>
						</Field.Field>
						<Field.Field>
							<Field.Label for="username">ONVIF Username</Field.Label>
							<Input id="username" placeholder="Username" bind:value={username} disabled={adding} />
						</Field.Field>
						<Field.Field>
							<Field.Label for="password">ONVIF Password</Field.Label>
							<Input
								id="password"
								type="password"
								placeholder="Password"
								bind:value={password}
								disabled={adding}
							/>
						</Field.Field>
						<Button type="submit" disabled={adding}>
							{#if adding}
								<Spinner />
							{/if}
							Add Camera
						</Button>
					</Field.Group>
				</Field.Set>
			</form>
		</div>
	</Drawer.Content>
</Drawer.Root>
