<script lang="ts">
	import { i18n } from '$lib/i18n';
	import Icon from '$lib/components/utils/Icon.svelte';
	import { login } from '$lib/api';
	import Modal from '$lib/components/layout/Modal.svelte';
	import { type UpendApiError } from '@upnd/upend/api';

	let username = '';
	let password = '';
	let error: string | undefined;
	let authenticating = false;

	async function submit() {
		error = undefined;
		try {
			authenticating = true;
			await login({ username, password });
		} catch (e) {
			error = (e as UpendApiError).message || (e as UpendApiError).kind;
		} finally {
			authenticating = false;
		}
	}
</script>

<Modal disabled={authenticating}>
	<h2>
		<Icon name="lock" />
		{$i18n.t('Authorization required')}
	</h2>
	<form on:submit|preventDefault={submit}>
		<input placeholder={$i18n.t('Username')} type="text" bind:value={username} required />
		<input placeholder={$i18n.t('Password')} type="password" bind:value={password} required />
		<button type="submit"> <Icon plain name="log-in" /> {$i18n.t('Login')}</button>
	</form>
	{#if error}
		<div class="error">{error}</div>
	{/if}
</Modal>

<style lang="scss">
	@use '$lib/styles/colors';

	h2 {
		text-align: center;
		margin: 0 0 1rem 0;
	}

	form {
		display: contents;
	}

	.error {
		color: colors.$red;
		text-align: center;
	}
</style>
