<template>
	<div v-if="success" class="w-full sm:max-w-sm sm:mx-auto sm:my-auto p-6 space-y-4 bg-white rounded-lg shadow-md text-center">
		<div class="text-center font-thin text-4xl pt-4">AUTOPLEX</div>
		<div>
			<i class="fas fa-check-circle align-middle text-green-500 text-4xl"></i>
		</div>
		<p>Discord account linked successfully! You may close this tab now</p>
	</div>
	<div v-else 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 pt-4">AUTOPLEX</div>
		<div>
			<p class="opacity-70 text-sm text-center">Enter your credientials to complete linking your Discord account</p>
		</div>
		<form @submit.prevent="authenticate">
			<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>
					<button :disabled="isSubmitting" class="block w-full rounded-full bg-indigo-500 text-white p-2 focus:outline-none">Link Discord Account</button>
				</div>
			</div>
		</form>
	</div>
</template>

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

export default defineComponent({
	components: {
		TextBox
	},
	data() {
		return {
			isSubmitting: false,
			success: false,
			fields: {
				email: "",
				password: ""
			},
		}
	},
	methods: {
		async authenticate() {
			if (this.isSubmitting) {
				return;
			}
			this.isSubmitting = true;
			try {
				// Send the request and wait far the response
				let response = await fetch(`/auth/link/discord/${this.$route.params["token"]}`, {
					method: "post",
					headers: { "Content-Type": "application/json" },
					body: JSON.stringify(this.fields)
				});
				this.isSubmitting = false;
				// Check the response for errors
				let body = await response.json();
				if (response.status !== 200) {
					if (response.status === 401) {
						body.errors = { "email": [ "Email or password is incorrect" ] };
					}
					for (let fieldName of ["email", "password"]) {
						let field = <any>this.$refs[fieldName];
						let message = <string>((<any>body.errors)[fieldName] ?? [""])[0];
						field.setErrorMessage(message);
					}
					return;
				}
			} catch(e) {
				console.error("Something went wrong logging in:", e);
				this.isSubmitting = false;
			}
			this.success = true;
		}
	},
	async beforeRouteEnter(to, from, next) {
		let token = to.params["token"];
		if (typeof token !== "string") {
			next({ name: "Home" });
			return;
		}
		// Verify that the token is valid. Redirect otherwise
		let response = await fetch(`/auth/link/verify/discord/${token}`, { method: "post" });
		if (response.status !== 200) {
			next({ name: "Home" });
			return;
		}
		next();
	}
});
</script>
