<script lang="ts">
	/* eslint-disable @typescript-eslint/no-explicit-any */
	import * as Form from '$lib/components/ui/form/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import * as Dialog from '$lib/components/ui/dialog/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import * as NativeSelect from '$lib/components/ui/native-select/index.js';
	let {
		editingUser,
		editForm,
		editData,
		enhanceEdit,
		onClose
	}: {
		editingUser: any;
		editForm: any;
		editData: any;
		enhanceEdit: any;
		onClose: () => void;
	} = $props();
</script>

<Dialog.Root open={!!editingUser} onOpenChange={(open) => !open && onClose()}>
	<Dialog.Content class="sm:max-w-md">
		<Dialog.Header>
			<Dialog.Title>Edit user</Dialog.Title>
			<Dialog.Description>Update account details or set a new password.</Dialog.Description>
		</Dialog.Header>
		{#if editingUser}
			<form method="POST" action="?/edit" class="grid gap-2" use:enhanceEdit>
				<input type="hidden" name="id" value={$editData.id} />
				<Form.Field form={editForm} name="name">
					<Form.Control id="edit-name">
						{#snippet children({ props })}
							<Form.Label>Name</Form.Label>
							<Input {...props} autocomplete="name" bind:value={$editData.name} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={editForm} name="email">
					<Form.Control id="edit-email">
						{#snippet children({ props })}
							<Form.Label>Email</Form.Label>
							<Input {...props} type="email" autocomplete="email" bind:value={$editData.email} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={editForm} name="password">
					<Form.Control id="edit-password">
						{#snippet children({ props })}
							<Form.Label>New password</Form.Label>
							<Input
								{...props}
								type="password"
								autocomplete="new-password"
								placeholder="Leave blank to keep current password"
								bind:value={$editData.password}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={editForm} name="role">
					<Form.Control id="edit-role">
						{#snippet children({ props })}
							<Form.Label>Role</Form.Label>
							<NativeSelect.Root {...props} bind:value={$editData.role} class="w-full">
								<NativeSelect.Option value="admin">Admin</NativeSelect.Option>
								<NativeSelect.Option value="user">User</NativeSelect.Option>
							</NativeSelect.Root>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Dialog.Footer>
					<Dialog.Close>
						{#snippet child({ props })}
							<Button variant="outline" {...props}>Cancel</Button>
						{/snippet}
					</Dialog.Close>
					<Button type="submit">Save changes</Button>
				</Dialog.Footer>
			</form>
		{/if}
	</Dialog.Content>
</Dialog.Root>
