<script lang="ts">
	import { untrack } from "svelte";
	import { resolve } from "$app/paths";
	import Avatar from "$lib/components/ui/Avatar.svelte";
	import Button from "$lib/components/ui/Button.svelte";
	import Select from "$lib/components/ui/Select.svelte";
	import SettingsBlock from "$lib/components/settings/SettingsBlock.svelte";
	import SettingsList from "$lib/components/settings/SettingsList.svelte";
	import SettingsRow from "$lib/components/settings/SettingsRow.svelte";
	import DocsButton from "$lib/components/settings/DocsButton.svelte";
	import Plus from "$icon/plus";
	import Trash from "$icon/trash-2";

	let { data } = $props();

	const base = $derived(`/${data.repo.ownerHandle}/${data.repo.name}/settings`);
	const path = (p: string) => resolve(p as "/");

	// mocked — spindle selection and secrets are not wired up yet
	let spindle = $state(untrack(() => data.repo.spindle) ?? "spindle.tangled.sh");
	const spindles = $derived([spindle, "spindle.user.tld"]);

	let secrets = $state([
		{
			name: "generic_secret",
			added: "Added 5 hours ago by",
			by: untrack(() => data.repo.ownerHandle)
		}
	]);

	const remove = (name: string) => {
		secrets = secrets.filter((s) => s.name !== name);
	};
</script>

<div class="flex min-h-8 w-full items-center gap-4">
	<h1 class="typography-heading-2 text-foreground-default">Pipelines</h1>
</div>

<SettingsBlock
	title="Spindle"
	description={[
		"Choose a spindle to execute your workflows on. Only repository owners can configure spindles.",
		"Spindles can be selfhosted."
	]}
	separator
>
	{#snippet action()}
		<DocsButton href="https://docs.tangled.org/spindles" />
	{/snippet}

	<SettingsList>
		<SettingsRow title="Spindle" stack>
			<Select
				bind:value={spindle}
				options={spindles.map((option) => ({ value: option }))}
				label="Spindle"
				class="w-full sm:w-80"
			/>
		</SettingsRow>
	</SettingsList>
</SettingsBlock>

<SettingsBlock
	title="Secrets"
	description={[
		"Secrets are accessible in workflow runs via environment variables.",
		"Anyone with collaborator access to this repository can add and use secrets in workflow runs."
	]}
	separator
>
	{#snippet action()}
		<Button icon={Plus} href={path(`${base}/pipelines/secrets/new`)}>Add secret</Button>
	{/snippet}

	<SettingsList>
		{#each secrets as secret (secret.name)}
			<SettingsRow stack>
				{#snippet label()}
					<span class="flex min-w-0 flex-col gap-1">
						<span class="font-mono typography-monospace-regular break-all text-foreground-default">
							{secret.name}
						</span>
						<span
							class="flex items-center gap-1.5 typography-paragraph-regular text-foreground-muted"
						>
							{secret.added}
							<Avatar handle={secret.by} size="small" />
							{secret.by}
						</span>
					</span>
				{/snippet}
				<Button variant="danger" icon={Trash} onclick={() => remove(secret.name)}>Delete</Button>
			</SettingsRow>
		{/each}
	</SettingsList>
</SettingsBlock>
