<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 { createAction } from "$lib/action.svelte";
	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("");

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

	const save = createAction(async () => {
		if (!auth.agent || !valid) return;
		await createPubKey(auth.agent, name.trim(), key.trim());
		await goto(resolve("/settings/keys"));
	});
	const submit = save.run;
</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."
>
	<ErrorAlert label={save.error} />

	<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={save.loading} onclick={submit}>
			Add
		</Button>
	</FormActions>
</DrillDown>
