<script setup lang="ts">
import {
    Card,
    CardHeader,
    CardTitle,
    CardDescription,
    CardContent,
    CardFooter,
} from '@/components/ui/card';
import { registerUser } from '~/lib/api/auth/register';

definePageMeta({
    layout: 'auth',
});

const registering = ref(false);
const username = ref('');
const email = ref('');
const password = ref('');

const allFieldsValid = computed(
    () =>
        username.value.trim().length > 0 &&
        email.value.trim().length > 0 &&
        password.value.trim().length > 0
);

async function submit() {
    registering.value = true;

    const { success } = await registerUser(
        username.value,
        email.value,
        password.value
    );

    if (success) {
        await navigateTo({ path: '/login' });
        return;
    }

    registering.value = false;
}
</script>

<template>
    <Card class="w-full max-w-sm">
        <CardHeader>
            <CardTitle class="text-2xl">Sign up</CardTitle>
            <CardDescription>Create a new user account</CardDescription>
        </CardHeader>
        <CardContent class="grid gap-4">
            <div class="grid gap-2">
                <Label for="username">Username</Label>
                <Input
                    id="username"
                    v-model="username"
                    type="username"
                    placeholder="409"
                    autocomplete="off"
                    required
                />
            </div>
            <div class="grid gap-2">
                <Label for="email">Email</Label>
                <Input
                    id="email"
                    v-model="email"
                    type="email"
                    placeholder="your@email.com"
                    autocomplete="off"
                    required
                />
            </div>
            <div class="grid gap-2">
                <Label for="password">Password</Label>
                <Input
                    id="password"
                    v-model="password"
                    type="password"
                    autocomplete="off"
                    required
                />
            </div>
        </CardContent>
        <CardFooter class="flex-col gap-2">
            <Button
                class="w-full"
                :disabled="!allFieldsValid || registering"
                @click="submit"
                >Sign up</Button
            >
            <NuxtLink to="/login" class="w-full">
                <Button class="w-full" variant="ghost">Sign in instead</Button>
            </NuxtLink>
        </CardFooter>
    </Card>
</template>
