<script lang="ts">
	import { signup, login } from '$lib/api/auth.remote';

	import * as Card from '$lib/components/ui/card/index.js';
	import * as Field from '$lib/components/ui/field/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { toast } from 'svelte-sonner';

	let { tabValue = $bindable() }: { tabValue: string } = $props();
</script>

<Card.Root class="w-full max-w-sm">
	<Card.Header>
		<Card.Title>Sign up for an account</Card.Title>
		<Card.Description>Enter your email below to register for an account</Card.Description>
	</Card.Header>

	<form
		{...signup.enhance(async ({ submit, element }) => {
			try {
				await submit();

				// Check if there are any validation issues
				const issues = signup.fields.allIssues();
				if (issues && issues.length > 0) {
					return;
				}

				// Move to login tab on success
				// TODO: Fix previous errors showing on login form
				element.reset();
				toast.success('Successfully registered!');
				login.fields.set({ email: '', password: '' });
				login.validate();
				tabValue = 'login';
			} catch (error) {
				console.error('Unknown error occurred: ', error);
				toast.error('Registration failed.');
			}
		})}
	>
		<Card.Content>
			<Field.Set>
				<Field.Group>
					<!-- Email field -->
					<Field.Field>
						<Field.Label for="email">Email</Field.Label>
						<Input {...signup.fields.email.as('email')} />
						{#each signup.fields.email.issues() ?? [] as issue, i (i)}
							<Field.Error>{issue.message}</Field.Error>
						{/each}
					</Field.Field>

					<!-- Password field -->
					<Field.Field>
						<Field.Label for="password">Password</Field.Label>
						<Input {...signup.fields.password.as('password')} />
						{#each signup.fields.password.issues() ?? [] as issue, i (i)}
							<Field.Error>{issue.message}</Field.Error>
						{/each}
					</Field.Field>

					<!-- Confirm password field -->
					<Field.Field>
						<Field.Label for="confirmPassword">Confirm Password</Field.Label>
						<Input {...signup.fields.confirmPassword.as('password')} />
						{#each signup.fields.confirmPassword.issues() ?? [] as issue, i (i)}
							<Field.Error>{issue.message}</Field.Error>
						{/each}
					</Field.Field>
				</Field.Group>
			</Field.Set>
		</Card.Content>

		<!-- Submit button -->
		<Card.Footer class="flex-col gap-2 pt-6">
			<Button type="submit" class="w-full">Sign Up</Button>
		</Card.Footer>
	</form>
</Card.Root>
