<template>
	<div class="w-full sm:max-w-sm sm:mx-auto sm:my-auto p-6 space-y-4 bg-white rounded-lg shadow-md">
		<div class="text-center font-thin text-4xl py-4 font-brand">AUTOPLEX</div>
		<div class="font-medium text-center text-xl">Sign in</div>
		<form @submit.prevent="login">
			<div class="space-y-4">
				<div>
					<text-box label="Email" type="email" ref="email" placeholder="john@example.com" :disabled="isSubmitting"
					v-model="fields.email"/>
				</div>
				<div>
					<text-box label="Password" type="password" ref="password" placeholder="············" :disabled="isSubmitting"
					v-model="fields.password"/>
				</div>
				<div>
					<check-box label="Remember Me" :disabled="isSubmitting" v-model="fields.remember"/>
				</div>
				<div>
					<button :disabled="isSubmitting" class="block w-full rounded-full bg-indigo-500 text-white p-2 focus:outline-none">Sign In</button>
				</div>
			</div>
		</form>
	</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { Action } from "../store";
import CheckBox from "../components/CheckBox.vue";
import TextBox from "../components/TextBox.vue";

export default defineComponent({
	components: {
		CheckBox,
		TextBox
	},
	data() {
		return {
			isSubmitting: false,
			fields: {
				email: "",
				password: "",
				remember: false
			}
		}
	},
	methods: {
		async login() {
			if (this.isSubmitting) {
				return;
			}
			this.isSubmitting = true;
			try {
				let errors = await this.$store.dispatch(Action.AuthLogin, this.fields);
				if (errors) {
					for (let fieldName of ["email", "password"]) {
						let field = <any>this.$refs[fieldName];
						let message = <string>((<any>errors)[fieldName] ?? [""])[0];
						field.setErrorMessage(message);
					}
				} else {
					this.$router.push({ name: "Home" });
				}
			} catch(e) {
				console.error("Something went wrong logging in:", e);
			}
			this.isSubmitting = false;
		}
	}
});
</script>

<style lang="postcss">
button:focus-visible {
	@apply ring-2 ring-indigo-500 ring-offset-2;
}
</style>
