<script lang="ts">
	import type { PageData } from './$types.js';
	import GroupTable from '$lib/components/admin/GroupTable.svelte';
	import { superForm } from 'sveltekit-superforms/client';

	let { data }: { data: PageData } = $props();

	let showCreateForm = $state(false);

	const { form, errors, enhance } = superForm(data.createForm, {
		resetForm: true,
		onResult: ({ result }) => {
			if (result.type === 'success') {
				showCreateForm = false;
			}
		}
	});
</script>

<svelte:head>
	<title>Group Management — Admin</title>
</svelte:head>

<div>
	<div class="mb-6 flex items-center justify-between">
		<h1 class="text-2xl font-bold text-card-foreground">Group Management</h1>
		<button
			type="button"
			onclick={() => (showCreateForm = !showCreateForm)}
			class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring"
		>
			{showCreateForm ? 'Cancel' : 'Create Group'}
		</button>
	</div>

	{#if showCreateForm}
		<div class="mb-6 rounded-lg border border-border bg-card p-6">
			<h2 class="mb-4 text-lg font-semibold text-card-foreground">New Group</h2>
			<form method="POST" action="?/create" use:enhance class="space-y-4">
				<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
					<div>
						<label for="name" class="mb-1 block text-sm font-medium text-foreground">Name</label>
						<input
							id="name"
							name="name"
							type="text"
							bind:value={$form.name}
							class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground"
							required
						/>
						{#if $errors.name}<span class="text-xs text-destructive">{$errors.name}</span>{/if}
					</div>
					<div>
						<label for="description" class="mb-1 block text-sm font-medium text-foreground">Description</label>
						<input
							id="description"
							name="description"
							type="text"
							bind:value={$form.description}
							class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground"
						/>
					</div>
					<div class="flex items-center gap-2">
						<input
							id="isDefault"
							name="isDefault"
							type="checkbox"
							bind:checked={$form.isDefault}
							class="h-4 w-4 rounded border-input"
						/>
						<label for="isDefault" class="text-sm font-medium text-foreground">Default group (auto-assign new users)</label>
					</div>
				</div>
				{#if $errors._errors}
					<p class="text-sm text-destructive">{$errors._errors}</p>
				{/if}
				<button
					type="submit"
					class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
				>
					Create Group
				</button>
			</form>
		</div>
	{/if}

	<GroupTable groups={data.groups} />
</div>
