<script>
	import { onMount } from 'svelte';

	import * as Card from '$lib/components/ui/card/index';
	import * as Select from '$lib/components/ui/select';
	import { Label } from '$lib/components/ui/label';
	import { db } from '../db/main';
	import { liveQuery } from 'dexie';
	import { shortforms } from '$lib/stores.svelte';
	import { cacheShortforms } from '../modules/shortforms';

	const onSelectedStandardListChange = (e) => {
		console.log('onSelectedStandardListChange', e);
		shortforms.standardList = e.value;
		cacheShortforms([Number(shortforms.standardList), Number(shortforms.subjectLists)]);
	};

	const onSelectedSubjectListChange = (e) => {
		console.log('onSelectedSubjectListChange', e);
		shortforms.subjectList = e.value;
		cacheShortforms([Number(shortforms.standardList), Number(shortforms.subjectList)]);
	};

	const onSubmit = (e) => {
		e.preventDefault();
		console.log('submit', listSelectorForm);
	};

	let listSelectorForm = {
		standard: { value: '', label: '' },
		subject: { value: '', label: '' }
	};

	let standardLists = [];
	let subjectLists = [];
	onMount(() => {
		db.lists.toArray().then((lists) => {
			standardLists = lists.filter((l) => l.type == 0);
			subjectLists = lists.filter((l) => l.type == 1);
		});
	});
</script>

<Card.Root class="mx-auto w-[490px]">
	<Card.Header>
		<Card.Title>Välj förkortningslistor</Card.Title>
		<Card.Description></Card.Description>
	</Card.Header>
	<Card.Content class="mx-auto">
		<form
			class="grid gap-4 py-4"
			method="post"
			enctype="multipart/form-data"
			onsubmit={onSubmit}
			autocomplete="off"
		>
			<div class="grid grid-cols-4 items-center gap-4">
				<Label>Standardlista</Label>
				<Select.Root
					selected={listSelectorForm.standard}
					onSelectedChange={onSelectedStandardListChange}
				>
					<Select.Trigger class="w-[290px]">
						<Select.Value placeholder="Ingen lista vald" />
					</Select.Trigger>

					<Select.Content>
						{#each standardLists as list}
							<Select.Item value={list.id} label={list.name}>{list.name}</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</div>
			<div class="grid grid-cols-4 items-center gap-4">
				<Label>Ämneslista</Label>
				<Select.Root
					selected={listSelectorForm.subject}
					onSelectedChange={onSelectedSubjectListChange}
					disabled={subjectLists.length < 1}
				>
					<Select.Trigger class="w-[290px]">
						<Select.Value placeholder="Ingen lista vald" />
					</Select.Trigger>

					<Select.Content>
						{#each subjectLists as list}
							<Select.Item value={list.id} label={list.name}>{list.name}</Select.Item>
						{/each}
					</Select.Content>
				</Select.Root>
			</div>
			<button type="submit" class="hidden" />
		</form>
	</Card.Content>
	<!--
	<Card.Footer class="flex justify-between">
		<Button on:click={cancelCreate} variant="outline">Avbryt</Button>
		<Button on:click={handleCreate}>Importera</Button>
	</Card.Footer>
	-->
</Card.Root>
