<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 Spool from "$icon/spool";
	import Check from "$icon/check";
	import X from "$icon/x";
	import RotateCcw from "$icon/rotate-ccw";

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

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

	const remove = (id: string) => {
		spindles = spindles.filter((s) => s.id !== id);
	};

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

<SettingsHeader title="Spindles" description="Spindles are small CI runners." />

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

	{#if spindles.length === 0}
		<SettingsEmpty message="No spindles registered yet" />
	{:else}
		<SettingsList>
			{#each spindles as spindle (spindle.id)}
				<SettingsEntry icon={Spool} title={spindle.hostname}>
					{#snippet tags()}
						{#if spindle.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">{spindle.added}</span>
					{/snippet}
					{#snippet actions()}
						{#if !spindle.verified}
							<Button icon={RotateCcw} onclick={() => retry(spindle.id)}>Retry</Button>
						{/if}
						<Button variant="danger" icon={Trash} onclick={() => remove(spindle.id)}>Delete</Button>
					{/snippet}
				</SettingsEntry>
			{/each}
		</SettingsList>
	{/if}
</div>
