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

	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>{$t('admin.group_management')} — {$t('admin.panel')}</title>
</svelte:head>

<div>
	<div class="mb-6 flex items-center justify-between">
		<h1 class="text-2xl font-bold text-card-foreground">{$t('admin.group_management')}</h1>
		<Button onclick={() => (showCreateForm = !showCreateForm)}>
			{showCreateForm ? $t('common.cancel') : $t('admin.create_group')}
		</Button>
	</div>

	{#if showCreateForm}
		<div class="mb-6 rounded-[1.4rem] border border-border bg-card p-6 shadow-[var(--shadow-soft)]">
			<h2 class="mb-4 text-lg font-semibold text-card-foreground">{$t('admin.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">{$t('common.name')}</label>
						<input
							id="name"
							name="name"
							type="text"
							bind:value={$form.name}
							class="w-full rounded-xl 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">{$t('common.description')}</label>
						<input
							id="description"
							name="description"
							type="text"
							bind:value={$form.description}
							class="w-full rounded-xl border border-input bg-background px-3 py-2 text-sm text-foreground"
						/>
					</div>
					<div class="flex items-center gap-3">
						<Switch
							id="isDefault"
							name="isDefault"
							bind:checked={$form.isDefault}
							ariaLabelledby="isDefaultLabel"
						/>
						<label id="isDefaultLabel" for="isDefault" class="cursor-pointer text-sm font-medium text-foreground">{$t('admin.default_group_hint')}</label>
					</div>
				</div>
				{#if $errors._errors}
					<p class="text-sm text-destructive">{$errors._errors}</p>
				{/if}
				<Button type="submit">{$t('admin.create_group')}</Button>
			</form>
		</div>
	{/if}

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