<script setup async>
import {computed, onMounted, reactive, ref, watch} from "vue";
import axios from "axios";
import {axiosPost, requestURl} from "@/utilities/request.js";
import {useRouter} from "vue-router";
import {clientStore} from "@/stores/clientStore.js";
import Qrcode from "@/components/SignIn/qrcode.vue";

const props = defineProps([
	'totpToken'
])
const totpKey = ref("")
const formData = reactive({
	TOTP: ""
})

const loading = ref(true)
const replace = () => {
	formData.TOTP = formData.TOTP.replace(/\D/i, "")
}
const formFilled = computed(() => {
	return /^[0-9]{6}$/.test(formData.TOTP)
})

const store = clientStore()
const router = useRouter()

onMounted(() => {
	axios.get(requestURl('/api/signin/totp'), {
		params: {
			Token: props.totpToken
		}
	}).then(res => {
		let data = res.data
		loading.value = false
		if (data.status){
			if (data.message){
				totpKey.value = data.message
			}
		}else{
			store.newNotification(data.message, "danger")
			router.push('/signin')
		}
	})
})

const emits = defineEmits(['clearToken'])
const verify = async (e) => {
	if (e) e.preventDefault()
	if (formFilled){
		loading.value = true
		const data = await axiosPost('/api/signin/totp', {
			Token: props.totpToken,
			UserProvidedTOTP: formData.TOTP
		})
		loading.value = false
		if (data){
			if (data.status){
				store.clientProfile = data.data;
				router.push('/')
			}else{
				store.newNotification(data.message, "danger")
			}
		}else{
			store.newNotification("Sign in status is invalid", "danger")
			emits('clearToken')
		}
	}
}

watch(formFilled, () => {
	verify()
})
</script>

<template>
<form class="d-flex flex-column gap-3" @submit="e => verify(e)">
	<div>
		<a role="button" @click="emits('clearToken')" class="btn btn-outline-body btn-sm rounded-3">
			<i class="me-2 bi bi-chevron-left"></i> Back
		</a>
	</div>
	<div>
		<h1 class="mb-3 text-center">Multi-Factor Authentication (MFA)</h1>
		<div class="card rounded-3 text-center" v-if="totpKey">
			<div class="card-body d-flex gap-3 flex-column align-items-center">
				<h2 class="mb-0">Initial Setup</h2>
				<p class="mb-0">Please scan the following QR Code to generate TOTP with your choice of authenticator</p>
				<Qrcode :content="totpKey"></Qrcode>
				<p class="mb-0">Or you can click the link below:</p>
				<div class="card rounded-3 w-100">
					<div class="card-body">
						<a :href="totpKey" style="text-wrap: auto">
							{{ totpKey }}
						</a>
					</div>
				</div>
				<div class="alert alert-warning mb-0 rounded-3">
					<strong>
						Please note: You won't be able to see this QR Code again, so please save it somewhere safe in case you need to recover your TOTP key
					</strong>
				</div>
			</div>
		</div>
	</div>
	<hr v-if="totpKey">
	<div class="d-flex flex-column gap-3 text-center">
		<label for="totp">Enter the TOTP generated by your authenticator to verify</label>
		<input class="form-control form-control-lg rounded-3 text-center"
		       id="totp"
		       :disabled="loading"
		       autofocus
		       @keyup="replace()"
		       maxlength="6" type="text" inputmode="numeric"
		       placeholder="- - - - - -"
		       autocomplete="one-time-code" v-model="formData.TOTP">

		<button
			:disabled="!formFilled || loading"
			class="btn btn-body rounded-3 px-3 py-2 fw-bold">
			<span v-if="!loading" class="d-block">
				Continue <i class="ms-2 bi bi-arrow-right"></i>
			</span>
			<span v-else class="d-block">
				Loading...
				<i class="ms-2 spinner-border spinner-border-sm"></i>
			</span>
		</button>
	</div>

</form>
</template>

<style scoped>
.card{
	background-color: rgba(0, 0, 0, 0.25);
	backdrop-filter: blur(8px);
}
</style>