<template>
	<div class="container box">
		<form @submit.prevent="handleSubmit">
			<div
				v-if="errorMessage"
				class="alert alert-danger mt-2"
			>
				{{ errorMessage }}
			</div>
			<div class="form-group mt-2">
				<label for="exampleInputEmail1">Username</label>
				<input
					id="username"
					v-model="username"
					type="text"
					class="form-control"
					aria-describedby="emailHelp"
					placeholder="Enter email"
				>
			</div>
			<div class="form-group mt-2">
				<label for="password">Password</label>
				<input
					id="password"
					v-model="password"
					type="password"
					class="form-control"
					placeholder="Password"
				>
			</div>
			<div class="form-check mt-2">
				<input
					id="remember-me"
					type="checkbox"
					class="form-check-input"
				>
				<label
					class="form-check-label"
					for="remember-me"
				>
					Remember Me
				</label>
			</div>
			<button
				type="submit"
				class="btn btn-primary mt-2 mb-2"
				:class="{ disabled: isLoading }"
			>
				Log in
			</button>
		</form>
	</div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import axios from 'axios'

const username = ref('')
const password = ref('')
const errorMessage = ref('')
const isLoading = ref(false)
const emit = defineEmits(['user-authenticated'])

const handleSubmit = () => {
	//console.log('handle submit')
	isLoading.value = true

	axios
		.post('/login', {
			username: username.value,
			password: password.value
		})
		.then((response) => {
			//console.log(response.headers)

			emit('user-authenticated', response.headers.location)
			username.value = ''
			password.value = ''
		})
		.catch((error) => {
			console.log(error)
			console.log(error.response.data)
			if (error.response.data.error) {
				errorMessage.value = error.response.data.error
			} else {
				errorMessage.value = 'Unknown error'
			}
		})
		.finally(() => {
			isLoading.value = false
		})
}
</script>

<style scoped lang="scss">
</style>
