<script lang="ts">
	import Plus from "$icon/plus";
	import Button from "$lib/components/ui/Button.svelte";
	import Field from "$lib/components/ui/Field.svelte";
	import Input from "$lib/components/ui/Input.svelte";
	import Textarea from "$lib/components/ui/Textarea.svelte";
	import KeyCard from "$lib/components/settings/KeyCard.svelte";
	import StepHeader from "./StepHeader.svelte";
	import { addKey, draft, removeKey } from "./draft.svelte";

	let name = $state("");
	let key = $state("");

	const canAdd = $derived(name.trim() !== "" && key.trim() !== "");

	const add = (event: SubmitEvent) => {
		event.preventDefault();
		if (!canAdd) return;
		addKey(name.trim(), key.trim());
		name = "";
		key = "";
	};
</script>

<div class="flex flex-col gap-6">
	<StepHeader
		title="Add an SSH key"
		subtitle="Add a public SSH key to push to your repositories over SSH."
	/>

	{#if draft.keys.length > 0}
		<ul class="flex flex-col gap-3">
			{#each draft.keys as pubkey (pubkey.id)}
				<li>
					<KeyCard
						name={pubkey.name}
						fingerprint={pubkey.fingerprint}
						createdAt={pubkey.createdAt}
						onDelete={() => removeKey(pubkey.id)}
					/>
				</li>
			{/each}
		</ul>
	{/if}

	<form class="flex flex-col gap-4" onsubmit={add}>
		<Field label="Key name" labelCase="normal">
			{#snippet children({ id })}
				<Input {id} placeholder="my-laptop" required bind:value={name} />
			{/snippet}
		</Field>

		<Field label="Public key" labelCase="normal">
			{#snippet children({ id })}
				<Textarea
					{id}
					size="compact"
					rows={3}
					required
					placeholder="ssh-ed25519 AAAA..."
					bind:value={key}
				/>
			{/snippet}
		</Field>

		<Button type="submit" icon={Plus} disabled={!canAdd} class="ml-auto">Add key</Button>
	</form>
</div>
