<template>
	<div class="container box">
		<form @submit.prevent="handleSubmit">
			<div
				v-if="error"
				class="alert alert-danger"
			>
				{{ error }}
			</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>
import axios from 'axios'

export default {
	name: 'LoginForm',
	/*
	props: {
		user: {
			Type: Object
		}
	},
	 */
	data() {
		return {
			username: '',
			password: '',
			error: '',
			isLoading: false
		}
	},
	methods: {
		handleSubmit() {
			console.log('handle submit')
			this.isLoading = true
			this.error = ''

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

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

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