<template>
	<div>
		<app-loading v-if="!isValid && loading"/>

		<div v-else-if="isValid" class="d-flex flex-column align-center container">
			<h1>Password Recovery</h1>
			<h2>Create your New Password</h2>

			<v-alert v-model="error.show" :type="error.type" class="mt-4" dismissible>
				{{ error.message }}
			</v-alert>

			<v-row class="w-100 my-10" tag="form" @submit.prevent="() => onSubmit($v)">
				<v-col cols="12">
					<v-text-field
						v-model.trim="form.password"
						:append-inner-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
						:error="$v.form.password.$dirty && $v.form.password.$error"
						:error-messages="getErrors($v.form.password)"
						:type="!showPassword ? 'password' : 'text'"
						hide-details="auto"
						label="Password"
						placeholder="Password*"
						required
						variant="outlined"
						@blur="$v.form.password.$touch()"
						@click:append-inner="showPassword = !showPassword"
					/>
				</v-col>
				<v-col class="py-0" cols="12">
					<v-text-field
						v-model.trim="form.password_confirmation"
						:append-inner-icon="
              showPasswordConfirmation ? 'mdi-eye' : 'mdi-eye-off'
            "
						:error="
              $v.form.password_confirmation.$dirty &&
              $v.form.password_confirmation.$error
            "
						:error-messages="getErrors($v.form.password_confirmation)"
						:type="!showPasswordConfirmation ? 'password' : 'text'"
						hide-details="auto"
						label="Confirm Password"
						placeholder="Confirm Password*"
						required
						variant="outlined"
						@blur="$v.form.password_confirmation.$touch()"
						@click:append-inner="
              showPasswordConfirmation = !showPasswordConfirmation
            "
					/>
				</v-col>
				<v-col cols="12">
					<v-btn
						:loading="loading"
						class="p-0 w-100"
						color="primary"
						size="large"
						type="submit"
						variant="elevated"
					>
						Save
					</v-btn>
				</v-col>
			</v-row>
		</div>

		<div v-else-if="!isValid && !loading" class="text-center my-5">
			This link is invalid.
		</div>
	</div>
</template>

<script setup>
const {computed, onMounted, ref} = Vue;
const {useVuelidate} = Vuelidate;
const {minLength, required, sameAs} = VuelidateValidators;

const AppLoading = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/AppLoading.vue`, options),
);

const showPasswordConfirmation = ref(false);
const showPassword = ref(false);
const loading = ref(false);
const error = ref({show: false, type: "error", message: ""});
const isValid = ref(false);
const store = useUserStore();
const form = ref({
	password: "",
	password_confirmation: "",
});
const agent = ref({});
const rules = {
	form: {
		password: {
			required,
			minLength: minLength(5),
		},
		password_confirmation: {
			required,
			sameAs: sameAs(computed(() => form.value.password)),
		},
	},
};
const $v = useVuelidate(rules, {form});

onMounted(async () => {
	document.title = "Recovery Password";
	await loadToken();
});

const recoveryBind = Vue.computed(() => {
	return {
		hash: window.location.pathname.split('/')[2],
	};
});

const loadToken = async () => {
	try {
		loading.value = true;
		const {data} = await axios.get(
			`/account/validate_token_recovery`,
			{params: {token: recoveryBind.value?.hash}},
		);
		agent.value = data.data;
		agent.value.token = recoveryBind.value?.hash;
		agent.value.vendor_id = agent.value.vendor ? agent.value.vendor.id : null;
		isValid.value = true;
	} catch (e) {
		console.log(e);
	} finally {
		loading.value = false;
	}
};

const onSubmit = async (submit) => {
	if (submit.$invalid) return;

	try {
		loading.value = true;

		const payload = {
			email: agent.value.login,
			password: form.value.password,
			token: recoveryBind.value?.hash,
		};

		const {data} = await axios.post(
			`/account/password_update`,
			payload,
		);
		if (data.success) {
			await store.setLoginUser({
				email: data.data.login,
				password: form.value.password,
			});
			await store.setSyncUser();

			window.location.href = `/${window.env?.sas_guest_panel_route}`;
		}
	} catch (e) {
		console.log(e);
	} finally {
		loading.value = false;
	}
};

const getErrors = ($v) => {
	if ($v.$dirty && $v.$errors?.length)
		return $v.$errors.map((e) => {
			switch (e.$validator) {
				case "sameAs":
					return "Passwords do not match";
				default:
					return e.$message;
			}
		});
	else return [];
};
</script>

<style scoped>
.container {
	max-width: 600px;
	margin: 15px auto;
}
</style>
