<script lang="ts" setup>
	import { reactive } from "vue";
	import { notification } from "ant-design-vue";
	interface FormState {
		username: string;
		password: string;
	}
	definePageMeta({
		auth: {
			unauthenticatedOnly: true,
			navigateAuthenticatedTo: "/",
		},
		middleware: ["auth"],
	});
	useHead({
		title: "Log In",
	});

	const formState = reactive<FormState>({
		username: "",
		password: "",
	});
	const darkRef = inject<Ref<boolean>>("dark");
	const onFinish = async (values: any) => {
		const { signIn } = useAuth();

		try {
			await signIn(values, { redirect: true, callbackUrl: "/" });
			const { data } = useAuth();
			darkRef.value = data.value.user.profile.nightMode;
			if (darkRef.value) document.body.dataset.theme = "dark";
			await navigateTo("/");
		} catch (e: any) {
			if (e.data) {
				notification["error"]({
					message: h("div", { innerHTML: e.data.message }),
				});
			}
		}
	};
</script>
<template>
	<a-form :model="formState" name="basic" :label-col="{ span: 8 }" autocomplete="off" :colon="false" layout="vertical" @finish="onFinish">
		<a-form-item label="Username" name="username" :rules="[{ required: true, message: 'Username required!' }]">
			<a-input data-testid="login.username" v-model:value="formState.username" />
		</a-form-item>
		<a-form-item :colon="false" label="Password" name="password" :rules="[{ required: true, message: 'Password required!' }]">
			<a-input-password data-testid="login.password" v-model:value="formState.password" />
		</a-form-item>
		<a-form-item>
			<a-row :justify="'center'" :align="'middle'">
				<a-col>
					<a-button data-testid="login.submit" type="primary" html-type="submit">Log in</a-button>
				</a-col>
			</a-row>
		</a-form-item>
	</a-form>
</template>
