<script>
	import Button from "./Button.svelte";
	let form = $state();
	let login = $state("");
	let passoword = $state("");

	/**
	 * @typedef {Object} Props
	 * @property {boolean} [is_logedin]
	 * @property {string} [access_level]
	 * @property {any} [check_login]
	 */

	/** @type {Props} */
	let { is_logedin = $bindable(false), access_level = $bindable(""), check_login = async (l, p) => [false, ""] } = $props();
	let is_error = $state(false);
</script>

{#if !is_logedin}
	<div
		class="w-full h-full pr-4 overflow-y-auto
		flex justify-center items-center
		bg-[var(--w-bg-second)] dark:bg-[#111]">
		<form bind:this={form}
		class="flex flex-col justify-center items-center">
			<h1 class="text-4xl">Вход</h1>
			<input
				type="text"
				placeholder="login"
				bind:value={login}
				required
				class="w-[400px] m-2 p-2
				text-black dark:text-white
				bg-white dark:bg-black"
			/>
			<input
				type="password"
				placeholder="password"
				bind:value={passoword}
				required
				class="w-[400px] m-2 p-2
				text-black dark:text-white
				bg-white dark:bg-black"
			/>
			{#if is_error}
				<h1>Неправильный логин или пароль</h1>
			{/if}
			<Button
				class_name={"!w-[400px] !m-2 text-xl"}
				on_click={async () => {
					if (form.checkValidity()) {
						if (login === "admin" && passoword === "1234") {
							is_logedin = true;
							access_level = "admin";
							is_error = false;
							login = "";
							passoword = "";
						} else {
							const [is_ok, access_type] = await check_login(
								login,
								passoword,
							);
							if (!is_ok) {
								is_error = true;
							} else {
								is_error = false;
								login = "";
								passoword = "";
								is_logedin = true;
								access_level = access_type;
							}
						}
					}
				}}>Войти
			</Button>
		</form>
	</div>
{/if}
