<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import Button from "$lib/components/ui/Button.svelte";
	import Input from "$lib/components/ui/Input.svelte";
	import Radio from "$lib/components/ui/Radio.svelte";
	import Checkbox from "$lib/components/ui/Checkbox.svelte";
	import DrillDown from "$lib/components/settings/DrillDown.svelte";
	import SettingsList from "$lib/components/settings/SettingsList.svelte";
	import FormRow from "$lib/components/settings/FormRow.svelte";
	import FormActions from "$lib/components/settings/FormActions.svelte";
	import Plus from "$icon/plus";
	import X from "$icon/x";

	let { data } = $props();

	const back = $derived(`/${data.repo.ownerHandle}/${data.repo.name}/settings`);

	// the eight swatches from the design
	const COLORS = [
		"#ef4444",
		"#3b82f6",
		"#22c55e",
		"#f59e0b",
		"#8b5cf6",
		"#ec4899",
		"#06b6d4",
		"#6b7280"
	];

	// mocked — custom labels are not wired up yet
	let type = $state<"basic" | "key-value">("basic");
	let name = $state("");
	let scopeIssues = $state(true);
	let scopePulls = $state(true);
	let color = $state(COLORS[0]);

	const valid = $derived(name.trim().length > 0 && (scopeIssues || scopePulls));
	const submit = () => goto(resolve(back as "/"));
</script>

<DrillDown backLabel="General" backHref={back} title="Add custom label">
	<SettingsList padding="tight">
		<FormRow
			label="Label type"
			description={[
				"Basic labels can have a name and a color.",
				"Key-value labels are more detailed, they can have a key and an associated value.",
				"You may define additional constraints on label values."
			]}
		>
			<div class="flex items-center gap-6">
				<Radio value="basic" bind:group={type} name="label-type">Basic</Radio>
				<Radio value="key-value" bind:group={type} name="label-type">Key-value</Radio>
			</div>
		</FormRow>

		<FormRow label="Name" for="label-name">
			<Input id="label-name" bind:value={name} placeholder="improvement" />
		</FormRow>

		<FormRow label="Scope" align="start">
			<div class="flex flex-col gap-1">
				<Checkbox bind:checked={scopeIssues}>Issues</Checkbox>
				<Checkbox bind:checked={scopePulls}>Pull requests</Checkbox>
			</div>
		</FormRow>

		<FormRow label="Color">
			<div class="flex items-center gap-2">
				{#each COLORS as swatch (swatch)}
					<button
						type="button"
						onclick={() => (color = swatch)}
						aria-label="Use colour {swatch}"
						aria-pressed={color === swatch}
						class="size-5 cursor-pointer rounded-full transition-shadow {color === swatch
							? 'ring-2 ring-foreground-default ring-offset-2 ring-offset-background-default'
							: ''}"
						style="background-color: {swatch}"
					></button>
				{/each}
			</div>
		</FormRow>
	</SettingsList>

	<FormActions>
		<Button href={resolve(back as "/")} icon={X}>Cancel</Button>
		<Button variant="primary" icon={Plus} disabled={!valid} onclick={submit}>Add</Button>
	</FormActions>
</DrillDown>
