<script lang="ts">
	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 Plus from "$icon/plus";
	import X from "$icon/x";

	interface Props {
		name?: string;
		key?: string;
		submitting?: boolean;
		error?: string | null;
		onSubmit: () => void;
		onCancel: () => void;
	}

	let {
		name = $bindable(""),
		key = $bindable(""),
		submitting = false,
		error = null,
		onSubmit,
		onCancel
	}: Props = $props();

	const handleSubmit = (e: SubmitEvent) => {
		e.preventDefault();
		onSubmit();
	};
</script>

<form onsubmit={handleSubmit} class="flex w-full flex-col gap-2">
	<label for="key-name" class="font-medium text-foreground-default">Add SSH key</label>
	<p class="text-sm text-foreground-subtle">
		SSH keys allow you to push to repositories in knots you're a member of.
	</p>
	<input
		id="key-name"
		type="text"
		placeholder="Key name"
		required
		bind:value={name}
		disabled={submitting}
		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"
	/>
	<textarea
		id="key-value"
		placeholder="ssh-ed25519 AAAAC3NzaC1..."
		required
		rows={3}
		spellcheck={false}
		bind:value={key}
		disabled={submitting}
		class="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 class="flex justify-end gap-2 pt-1">
		<Button type="button" icon={X} onclick={onCancel} disabled={submitting}>Cancel</Button>
		<Button
			type="submit"
			variant="primary"
			icon={submitting ? Spinner : Plus}
			disabled={submitting}
		>
			Add
		</Button>
	</div>
	{#if error}
		<ErrorAlert label={error} />
	{/if}
</form>
