<script lang="ts">
	import { goto } from "$app/navigation";
	import { ok } from "@atcute/client";
	import { mainSchema as createRecordSchema } from "@atcute/atproto/types/repo/createRecord";
	import type { Nsid } from "@atcute/lexicons/syntax";
	import { getAuth } from "$lib/auth.svelte";
	import { createClient } from "$lib/auth/agent";
	import { rkeyFromUri } from "$lib/api/uri";
	import Button from "$lib/components/ui/Button.svelte";
	import Spinner from "$lib/components/ui/Spinner.svelte";
	import ErrorAlert from "$lib/components/ui/Error.svelte";
	import ArrowUp from "$icon/arrow-up";

	const auth = getAuth();
	const user = $derived(auth.currentUser);

	let filename = $state("");
	let description = $state("");
	let content = $state("");
	let isPublishing = $state(false);
	let error = $state<string | null>(null);

	const lineCount = $derived(content === "" ? 0 : content.split("\n").length);
	const byteCount = $derived(new TextEncoder().encode(content).length);

	const handleSubmit = async (e: SubmitEvent) => {
		e.preventDefault();
		if (!auth.agent) return;
		isPublishing = true;
		error = null;
		try {
			const rpc = createClient(auth.agent);
			const result = await ok(
				rpc.call(createRecordSchema, {
					input: {
						repo: auth.agent.sub,
						collection: "sh.tangled.string" as Nsid,
						record: {
							$type: "sh.tangled.string",
							filename,
							description,
							contents: content,
							createdAt: new Date().toISOString()
						}
					}
				})
			);
			const rkey = rkeyFromUri(result.uri);
			await goto(`/strings/${user?.handle}/${rkey}`);
		} catch (err) {
			error = err instanceof Error ? err.message : "Failed to publish string";
		} finally {
			isPublishing = false;
		}
	};
</script>

<svelte:head>
	<title>New string &middot; Tangled</title>
</svelte:head>

<div class="mx-auto w-full max-w-screen-lg px-4 py-12">
	<div class="px-2 py-2">
		<h1 class="text-xl font-bold text-foreground-default">Create a new string</h1>
		<p class="text-sm text-foreground-subtle">Store and share code snippets with ease.</p>
	</div>

	<div class="mt-4 rounded border border-border-default bg-background-default">
		<form onsubmit={handleSubmit}>
			<div class="flex flex-col gap-2 p-4">
				<div class="flex flex-col gap-2 md:flex-row">
					<input
						type="text"
						id="filename"
						name="filename"
						placeholder="Filename"
						required
						bind:value={filename}
						disabled={isPublishing}
						class="rounded border border-border-default bg-background-default px-2 py-2 text-sm text-foreground-default placeholder:text-foreground-placeholder focus:ring-1 focus:ring-border-strong focus:outline-none disabled:opacity-50 md:max-w-64"
					/>
					<input
						type="text"
						id="description"
						name="description"
						placeholder="Description ..."
						maxlength={280}
						bind:value={description}
						disabled={isPublishing}
						class="flex-1 rounded border border-border-default bg-background-default px-2 py-2 text-sm text-foreground-default placeholder:text-foreground-placeholder focus:ring-1 focus:ring-border-strong focus:outline-none disabled:opacity-50"
					/>
				</div>

				<textarea
					id="content"
					name="content"
					placeholder="Paste your string here!"
					required
					rows={20}
					spellcheck={false}
					bind:value={content}
					disabled={isPublishing}
					class="w-full resize-y rounded border border-border-default bg-background-default px-2 py-2 font-mono text-sm text-foreground-default placeholder:text-foreground-placeholder focus:ring-1 focus:ring-border-strong focus:outline-none disabled:opacity-50"
				></textarea>
			</div>

			<div class="flex items-center justify-between px-4 py-3">
				<div class="text-sm text-foreground-subtle">
					<span>{lineCount} line{lineCount !== 1 ? "s" : ""}</span>
					<span class="px-1 select-none">·</span>
					<span>{byteCount} byte{byteCount !== 1 ? "s" : ""}</span>
				</div>

				<Button
					type="submit"
					variant="primary"
					icon={isPublishing ? Spinner : ArrowUp}
					disabled={isPublishing}
				>
					Publish
				</Button>
			</div>

			{#if error}
				<div class="px-4 pb-4">
					<ErrorAlert label={error} />
				</div>
			{/if}
		</form>
	</div>
</div>
