<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import { getAuth } from "$lib/auth.svelte";
	import { createPubKey } from "$lib/api/settings";
	import Button from "$lib/components/ui/Button.svelte";
	import Input from "$lib/components/ui/Input.svelte";
	import ErrorAlert from "$lib/components/ui/Error.svelte";
	import DrillDown from "$lib/components/settings/DrillDown.svelte";
	import SettingsList from "$lib/components/settings/SettingsList.svelte";
	import FormRow from "$lib/components/settings/FormRow.svelte";
	import FormActions from "$lib/components/settings/FormActions.svelte";
	import Plus from "$icon/plus";
	import X from "$icon/x";

	const auth = getAuth();

	let name = $state("");
	let key = $state("");
	let submitting = $state(false);
	let error = $state<string | null>(null);

	const valid = $derived(name.trim().length > 0 && key.trim().length > 0);

	const submit = async () => {
		if (!auth.agent || !valid) return;
		submitting = true;
		error = null;
		try {
			await createPubKey(auth.agent, name.trim(), key.trim());
			await goto(resolve("/settings/keys"));
		} catch (err) {
			error = err instanceof Error ? err.message : "Failed to add key";
			submitting = false;
		}
	};
</script>

<DrillDown
	backLabel="Keys"
	backHref="/settings/keys"
	title="Add SSH key"
	description="SSH keys allow you to push to repositories in knots you're a member of."
>
	{#if error}
		<ErrorAlert label={error} />
	{/if}

	<SettingsList padding="tight">
		<FormRow label="Title" for="key-title">
			<Input id="key-title" bind:value={name} placeholder="Work laptop" />
		</FormRow>
		<FormRow label="Key" for="key-value">
			<Input id="key-value" bind:value={key} placeholder="ssh-ed25519 AAAAB3NzaC1yc2E…" />
		</FormRow>
	</SettingsList>

	<FormActions>
		<Button href="/settings/keys" icon={X}>Cancel</Button>
		<Button variant="primary" icon={Plus} disabled={!valid} loading={submitting} onclick={submit}>
			Add
		</Button>
	</FormActions>
</DrillDown>
