<script lang="ts">
	import Button from "$lib/components/ui/Button.svelte";
	import Tag from "$lib/components/ui/Tag.svelte";
	import SettingsEmpty from "../SettingsEmpty.svelte";
	import SettingsHeader from "../SettingsHeader.svelte";
	import SettingsToolbar from "../SettingsToolbar.svelte";
	import SettingsList from "../SettingsList.svelte";
	import SettingsEntry from "../SettingsEntry.svelte";
	import Plus from "$icon/plus";
	import Trash from "$icon/trash-2";
	import DocsButton from "../DocsButton.svelte";
	import Server from "$icon/server";
	import Check from "$icon/check";
	import X from "$icon/x";
	import RotateCcw from "$icon/rotate-ccw";

	interface MockKnot {
		id: string;
		hostname: string;
		verified: boolean;
		added: string;
	}

	// mocked — knot registration is not wired up yet
	let knots = $state<MockKnot[]>([
		{ id: "1", hostname: "knot2.user.tld", verified: true, added: "Added 5 hours ago" },
		{ id: "2", hostname: "knot.user.tld", verified: false, added: "Added 6 months ago" }
	]);

	const remove = (id: string) => {
		knots = knots.filter((k) => k.id !== id);
	};

	const retry = (id: string) => {
		knots = knots.map((k) => (k.id === id ? { ...k, verified: true } : k));
	};
</script>

<SettingsHeader
	title="Knots"
	description="Knots are lightweight headless servers that enable users to host Git repositories with ease. When creating a repository, you can choose a knot to store it on."
/>

<div class="flex w-full flex-col gap-4">
	<SettingsToolbar>
		{#snippet start()}
			<DocsButton href="https://docs.tangled.org/knots" />
		{/snippet}
		{#snippet end()}
			<Button href="/settings/knots/new" icon={Plus}>Register a knot</Button>
		{/snippet}
	</SettingsToolbar>

	{#if knots.length === 0}
		<SettingsEmpty message="No knots registered yet" />
	{:else}
		<SettingsList>
			{#each knots as knot (knot.id)}
				<SettingsEntry icon={Server} title={knot.hostname}>
					{#snippet tags()}
						{#if knot.verified}
							<Tag color="success" size="sm" icon={Check}>Verified</Tag>
						{:else}
							<Tag color="warning" size="sm" icon={X}>Unverified</Tag>
						{/if}
					{/snippet}
					{#snippet meta()}
						<span class="typography-paragraph-regular text-foreground-muted">{knot.added}</span>
					{/snippet}
					{#snippet actions()}
						{#if !knot.verified}
							<Button icon={RotateCcw} onclick={() => retry(knot.id)}>Retry</Button>
						{/if}
						<Button variant="danger" icon={Trash} onclick={() => remove(knot.id)}>Delete</Button>
					{/snippet}
				</SettingsEntry>
			{/each}
		</SettingsList>
	{/if}
</div>
