<script lang="ts">
	import ArrowLeftIcon from '@lucide/svelte/icons/arrow-left';
	import ArrowRightIcon from '@lucide/svelte/icons/arrow-right';
	import GalleryVerticalEndIcon from '@lucide/svelte/icons/gallery-vertical-end';
	import { toast } from 'svelte-sonner';
	import * as Form from '$lib/components/ui/form/index.js';
	import * as Field from '$lib/components/ui/field/index.js';
	import * as Stepper from '$lib/components/ui/stepper/index.js';
	import { superForm, type SuperValidated } from 'sveltekit-superforms';
	import { zod4Client } from 'sveltekit-superforms/adapters';
	import type { HTMLAttributes } from 'svelte/elements';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import { cn, type WithElementRef } from '$lib/utils/format.js';
	import { firstFormError } from '$lib/utils/feedback';
	import { firstAdminSchema, type FirstAdminSchema } from '$lib/schemas/auth';

	let {
		ref = $bindable(null),
		class: className,
		form: initialForm,
		...restProps
	}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
		form: SuperValidated<FirstAdminSchema['_output'], string>;
	} = $props();

	const id = $props.id();
	let step = $state(0);

	const steps = [
		{ title: 'Admin', description: 'Account details' },
		{ title: 'Organization', description: 'Address details' },
		{ title: 'Bank', description: 'Payment details' }
	] as const;

	type FirstAdminField = keyof FirstAdminSchema['_output'];

	const stepFields = [
		['name', 'email', 'password', 'confirmPassword'],
		[
			'organizationName',
			'addressLine1',
			'addressLine2',
			'addressLine3',
			'city',
			'region',
			'postcode',
			'country'
		],
		['bankName', 'bankAccountName', 'bankAccountNumber', 'bankSortCode', 'bankIban', 'bankSwift']
	] satisfies FirstAdminField[][];

	function goToFirstErrorStep(errors: Partial<Record<FirstAdminField, unknown>>) {
		const errorStep = stepFields.findIndex((fields) =>
			fields.some((field) => {
				const error = errors[field];
				return Array.isArray(error) ? error.length > 0 : Boolean(error);
			})
		);

		if (errorStep >= 0) {
			step = errorStep;
		}
	}

	// svelte-ignore state_referenced_locally
	const firstAdminForm = superForm(initialForm, {
		validators: zod4Client(firstAdminSchema),
		resetForm: false,
		onUpdated: ({ form }) => {
			if (!form.valid) {
				goToFirstErrorStep(form.errors as Partial<Record<FirstAdminField, unknown>>);
				toast.error(form.message ?? firstFormError(form.errors), {
					id: 'first-admin-error',
					position: 'top-center'
				});
			}
		},
		onError: ({ result }) => {
			toast.error(result.error.message, {
				id: 'first-admin-error',
				position: 'top-center'
			});
		}
	});

	const { form: formData, enhance } = firstAdminForm;
</script>

<div class={cn('flex flex-col gap-6', className)} bind:this={ref} {...restProps}>
	<form method="POST" action="?/bootstrap" use:enhance>
		<Field.Group>
			<div class="flex flex-col items-center gap-2 text-center">
				<div class="flex flex-col items-center gap-2 font-medium">
					<div
						class="flex size-9 items-center justify-center rounded-md bg-primary text-primary-foreground"
					>
						<GalleryVerticalEndIcon class="size-6" />
					</div>
					<span class="sr-only">Clearity</span>
				</div>
				<h1 class="text-xl font-bold">First Time Setup</h1>
				<Field.Description class="text-center">Setup your initial admin account, organisation and bank details</Field.Description>
			</div>

			<Stepper.Root bind:value={step}>
				{#each steps as currentStep, index (currentStep.title)}
					<Stepper.Item step={index}>
						<div class="flex flex-col items-center gap-2 text-center">
							<Stepper.Indicator step={index} />
							<div class="grid gap-1">
								<Stepper.Title>{currentStep.title}</Stepper.Title>
								<Stepper.Description>{currentStep.description}</Stepper.Description>
							</div>
						</div>
						{#if index < steps.length - 1}
							<Stepper.Separator />
						{/if}
					</Stepper.Item>
				{/each}
			</Stepper.Root>

			<div class={['grid gap-4', step !== 0 && 'hidden']}>
				<Form.Field form={firstAdminForm} name="name">
					<Form.Control id={`name-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Name</Form.Label>
							<Input
								{...props}
								autocomplete="name"
								placeholder="Jane Smith"
								bind:value={$formData.name}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="email">
					<Form.Control id={`email-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Email</Form.Label>
							<Input
								{...props}
								type="email"
								autocomplete="email"
								placeholder="admin@example.com"
								bind:value={$formData.email}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="password">
					<Form.Control id={`password-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Password</Form.Label>
							<Input
								{...props}
								type="password"
								autocomplete="new-password"
								bind:value={$formData.password}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="confirmPassword">
					<Form.Control id={`confirm-password-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Confirm password</Form.Label>
							<Input
								{...props}
								type="password"
								autocomplete="new-password"
								bind:value={$formData.confirmPassword}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
			</div>

			<div class={['grid gap-4', step !== 1 && 'hidden']}>
				<Form.Field form={firstAdminForm} name="organizationName">
					<Form.Control id={`organization-name-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Organization</Form.Label>
							<Input
								{...props}
								autocomplete="organization"
								placeholder="Steel City Stadium"
								bind:value={$formData.organizationName}
							/>
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="addressLine1">
					<Form.Control id={`address-line-1-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Address line 1</Form.Label>
							<Input {...props} type="text" bind:value={$formData.addressLine1} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="addressLine2">
					<Form.Control id={`address-line-2-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Address line 2</Form.Label>
							<Input {...props} type="text" bind:value={$formData.addressLine2} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="addressLine3">
					<Form.Control id={`address-line-3-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Address line 3</Form.Label>
							<Input {...props} type="text" bind:value={$formData.addressLine3} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<div class="grid gap-4 sm:grid-cols-2">
					<Form.Field form={firstAdminForm} name="city">
						<Form.Control id={`city-${id}`}>
							{#snippet children({ props })}
								<Form.Label>City</Form.Label>
								<Input {...props} type="text" bind:value={$formData.city} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
					<Form.Field form={firstAdminForm} name="region">
						<Form.Control id={`region-${id}`}>
							{#snippet children({ props })}
								<Form.Label>Region</Form.Label>
								<Input {...props} type="text" bind:value={$formData.region} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
				</div>
				<div class="grid gap-4 sm:grid-cols-2">
					<Form.Field form={firstAdminForm} name="postcode">
						<Form.Control id={`postcode-${id}`}>
							{#snippet children({ props })}
								<Form.Label>Postcode</Form.Label>
								<Input {...props} type="text" bind:value={$formData.postcode} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
					<Form.Field form={firstAdminForm} name="country">
						<Form.Control id={`country-${id}`}>
							{#snippet children({ props })}
								<Form.Label>Country</Form.Label>
								<Input {...props} type="text" bind:value={$formData.country} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
				</div>
			</div>

			<div class={['grid gap-4', step !== 2 && 'hidden']}>
				<Form.Field form={firstAdminForm} name="bankName">
					<Form.Control id={`bank-name-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Bank name</Form.Label>
							<Input {...props} type="text" bind:value={$formData.bankName} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<Form.Field form={firstAdminForm} name="bankAccountName">
					<Form.Control id={`bank-account-name-${id}`}>
						{#snippet children({ props })}
							<Form.Label>Account name</Form.Label>
							<Input {...props} type="text" bind:value={$formData.bankAccountName} />
						{/snippet}
					</Form.Control>
					<Form.FieldErrors />
				</Form.Field>
				<div class="grid gap-4 sm:grid-cols-2">
					<Form.Field form={firstAdminForm} name="bankAccountNumber">
						<Form.Control id={`bank-account-number-${id}`}>
							{#snippet children({ props })}
								<Form.Label>Account number</Form.Label>
								<Input {...props} type="text" bind:value={$formData.bankAccountNumber} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
					<Form.Field form={firstAdminForm} name="bankSortCode">
						<Form.Control id={`bank-sort-code-${id}`}>
							{#snippet children({ props })}
								<Form.Label>Sort code</Form.Label>
								<Input {...props} type="text" bind:value={$formData.bankSortCode} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
				</div>
				<div class="grid gap-4 sm:grid-cols-2">
					<Form.Field form={firstAdminForm} name="bankIban">
						<Form.Control id={`bank-iban-${id}`}>
							{#snippet children({ props })}
								<Form.Label>IBAN</Form.Label>
								<Input {...props} type="text" bind:value={$formData.bankIban} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
					<Form.Field form={firstAdminForm} name="bankSwift">
						<Form.Control id={`bank-swift-${id}`}>
							{#snippet children({ props })}
								<Form.Label>SWIFT/BIC</Form.Label>
								<Input {...props} type="text" bind:value={$formData.bankSwift} />
							{/snippet}
						</Form.Control>
						<Form.FieldErrors />
					</Form.Field>
				</div>
			</div>

			<div class="grid gap-3 sm:grid-cols-2">
				{#if step > 0}
					<Button type="button" variant="outline" onclick={() => (step -= 1)}>
						<ArrowLeftIcon data-icon="inline-start" />Back
					</Button>
				{/if}
				{#if step < steps.length - 1}
					<Button
						type="button"
						class={step === 0 ? 'sm:col-start-2' : ''}
						onclick={() => (step += 1)}
					>
						Next step<ArrowRightIcon data-icon="inline-end" />
					</Button>
				{:else}
					<Button type="submit">Create admin</Button>
				{/if}
			</div>
		</Field.Group>
	</form>
</div>
