<script lang="ts">
	import { supabase } from '../../supabaseClient';
	import { onMount } from 'svelte';

	let email = '';

	onMount(async () => {
		const { data, error } = await supabase.auth.getSession();
		if (error) {
			alert(error.message);
		} else {
			email = data.session?.user?.email ?? '';

			console.log('email', email);
		}
	});

	async function changePassword() {
		const { data, error } = await supabase.auth.getUser();

		if (data.user) {
			const newPassword = (document.getElementById('new_password') as HTMLInputElement)?.value;
			const confirmPassword = (document.getElementById('confirm_password') as HTMLInputElement)
				?.value;

			if (newPassword === confirmPassword) {
				const { data, error } = await supabase.auth.updateUser({
					password: newPassword
				});

				if (error) {
					alert(error.message);
				} else {
					alert('Password changed successfully!');
				}
			} else {
				alert('Passwords do not match!');
			}
		} else {
			alert('You must be logged in to change your password!');
		}
	}
</script>

<div>
	<form
		class="max-w-lg mx-auto border-2 border-zinc-700 p-10 rounded-lg badge-glass flex flex-col gap-4"
		on:submit|preventDefault={changePassword}
	>
		<label for="email" class="label">Sähköposti:</label>
		<input class="input" type="email" name="email" id="email" value={email} />
		<hr />
		<p>Vaihda salasana</p>

		<label for="new_password" class="label">Uusi salasana:</label>
		<input class="input" type="password" name="new_password" id="new_password" />
		<label for="confirm_password" class="label">Vahvista uusi salasana:</label>
		<input class="input" type="password" name="confirm_password" id="confirm_password" />
		<button class="btn variant-filled" type="submit">Vaihda salasana</button>
	</form>
</div>
