<script lang="ts">
	import Button from "$lib/components/ui/button/button.svelte";
	import LabelWrapper from "$lib/components/atoms/label-wrapper.svelte";
	import Input from "$lib/components/ui/input/input.svelte";
	import * as Select from "$lib/components/ui/select";
	import * as Dialog from "$lib/components/ui/dialog/index.js";
	import { buttonVariants } from "$lib/components/ui/button";
	import { cn } from "$lib/utils";
	import { userVM } from "./user.vm.svelte";
	import { UserRoleMap } from "$lib/core/enums";
	import type { SelectOption } from "$lib/core/data.types";
	import { capitalize } from "$lib/core/string.utils";

	let open = $state(false);

	let chosenOpt = $state<SelectOption | undefined>(undefined);

	const opts = [
		{
			id: 0,
			label: capitalize(UserRoleMap.AGENT),
			value: UserRoleMap.AGENT,
		},
		{
			id: 1,
			label: capitalize(UserRoleMap.SUPERVISOR),
			value: UserRoleMap.SUPERVISOR,
		},
	];

	function setOpt(val: string) {
		chosenOpt = opts.find((e) => e.value === val);
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Trigger class={cn(buttonVariants({ variant: "ghost" }))}>
		Create User
	</Dialog.Trigger>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>Create new user</Dialog.Title>
		</Dialog.Header>
		<form
			class="flex flex-col gap-4 py-4"
			onsubmit={async (e) => {
				const ok = await userVM.onCreateUserFormSubmit(e);
				if (ok) {
					open = false;
					window.location.reload();
				}
			}}
		>
			<LabelWrapper label="User Type">
				<Select.Root
					type="single"
					required
					onValueChange={(e) => {
						console.log("Selected ::  ", e);
						setOpt(e);
					}}
					name="role"
				>
					<Select.Trigger class="w-full">
						{capitalize(
							opts?.find((e) => e.value === chosenOpt?.value)
								?.label ?? "Select",
						)}
					</Select.Trigger>
					<Select.Content>
						{#each opts as each}
							<Select.Item value={each.value}>
								{each.label}
							</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</LabelWrapper>

			<LabelWrapper label="Username">
				<Input name="username" required minlength={4} maxlength={128} />
			</LabelWrapper>

			<LabelWrapper label="Email">
				<Input
					name="email"
					type="email"
					required
					minlength={6}
					maxlength={128}
				/>
			</LabelWrapper>

			<LabelWrapper label="Password">
				<Input
					name="password"
					type="password"
					required
					minlength={8}
					maxlength={128}
				/>
			</LabelWrapper>

			<Button disabled={userVM.creatingUser} type="submit">
				{userVM.creatingUser ? "Creating..." : "Confirm & Create"}
			</Button>
		</form>
	</Dialog.Content>
</Dialog.Root>
