<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 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/hooks`);

	let url = $state("");
	let secret = $state("");
	// mocked — webhooks are not wired up yet. Push is preselected, as in the design.
	let events = $state<Record<string, boolean>>({
		push: true,
		renamed: false,
		opened: false,
		resubmitted: false,
		merged: false,
		closed: false,
		reopened: false
	});

	const EVENTS: { id: string; label: string }[] = [
		{ id: "push", label: "Push events" },
		{ id: "renamed", label: "Repository renamed" },
		{ id: "opened", label: "Pull request opened" },
		{ id: "resubmitted", label: "Pull request resubmitted" },
		{ id: "merged", label: "Pull request merged" },
		{ id: "closed", label: "Pull request closed" },
		{ id: "reopened", label: "Pull request reopened" }
	];

	const valid = $derived(url.trim().length > 0 && Object.values(events).some(Boolean));
	const submit = () => goto(resolve(back as "/"));
</script>

<DrillDown backLabel="Hooks" backHref={back} title="New webhook">
	<SettingsList padding="tight">
		<FormRow
			label="Payload URL"
			description="The URL that will receive the webhook POST requests."
			for="hook-url"
		>
			<Input id="hook-url" bind:value={url} placeholder="https://example.com/webhook" />
		</FormRow>

		<FormRow
			label="Secret"
			optional
			description="If provided, webhook payloads will be signed with HMAC-SHA256. Leave blank to send unsigned webhooks."
			for="hook-secret"
		>
			<Input id="hook-secret" bind:value={secret} placeholder="A secret for signed webhooks" />
		</FormRow>

		<FormRow
			label="Events"
			description="Additional event types (issues) will be available in future updates."
			align="start"
		>
			<div class="flex flex-col gap-1">
				{#each EVENTS as event (event.id)}
					<Checkbox bind:checked={events[event.id]}>{event.label}</Checkbox>
				{/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>
