<script lang="ts">
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import { clickOutside } from 'svelte-outside';
	import { appState, shortforms, importState } from '$lib/stores.svelte';
	import * as Card from '$lib/components/ui/card/index.js';
	import { Input } from '$lib/components/ui/input';
	import * as Select from '$lib/components/ui/select';
	import { Label } from '$lib/components/ui/label';
	import Button from '$lib/components/ui/button/button.svelte';
	import { Switch } from '$lib/components/ui/switch/index.js';
	import { Progress } from '$lib/components/ui/progress';
	import { Badge } from '$lib/components/ui/badge';
	import { Separator } from '$lib/components/ui/separator';
	import { db, createShortform, type List, type Shortform } from '../db/main';
	import { cacheShortform } from '../modules/shortforms';
	import { liveQuery } from 'dexie';

	import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';

	$: abbForm = {
		shortform: '',
		phrase: '',
		target: { value: -1 },
		errors: []
	};

	let importing = false;
	let progress = 0;
	const handleCreate = async (e: Event) => {
		//		abbForm.errors = []
		e.preventDefault();

		/*
	    id?: number;
	    listid: number;
	    shortform: string;
	    phrase: string;
	    used: Date;
	    uses: number;
	    remind: number, // negative if disabled
	    updated: Date;
    */
		var sf = {
			id: null,
			listid: abbForm.target.value,
			shortform: abbForm.shortform.replace(/\s/g, '').toLowerCase(),
			phrase: abbForm.phrase.trim(),
			last_used: new Date(0),
			uses: 0,
			remind: 0,
			updated: Date.now()
		};
		//appState.open = ""
		db.shortforms
			.where('[listid+shortform]')
			.equals([sf.listid, sf.shortform])
			.first()
			.then((existing) => {
				if (existing?.id) {
					sf.id = Number(existing.id);
					db.shortforms.put(sf).then((result) => {
						cacheShortform(sf);
						appState.open = '';
					});
				}
			})
			.catch(() => {
				db.shortforms.put(sf).then((result) => {
					cacheShortform(sf);
					appState.open = '';
				});
			});
	};
	const cancelCreate = () => {
		if (show) {
			abbForm.shortform = '';
			abbForm.phrase = '';
			abbForm.target = {};
			abbForm.errors = [];
			appState.open = '';
			show = false;
		}
	};

	const onSelectedChange = (v) => {
		console.log(typeof v, v);
		abbForm.target = v;
	};

	$: selectedLists = {
		standard: { label: '', value: -1 },
		subject: { label: '', value: -1 }
	};
	let show = false;

	db.lists
		.get(shortforms.standardList.id)
		.then((l) => {
			if (l) {
				selectedLists.standard = { value: l.id, label: l.name };
				abbForm.target = { value: l.id, label: l.name };
			} else {
				selectedLists.standard = { value: -1 };
			}
		})
		.catch((err) => {
			console.error('db.lists.get (standard)', err);
		});
	db.lists
		.get(shortforms.subjectList.id)
		.then((l) => {
			if (l) {
				selectedLists.subject = { value: l.id, label: l.name };
				abbForm.target = { value: l.id, label: l.name };
			} else {
				selectedLists.subject = { value: -1 };
			}
		})
		.catch((err) => {
			console.error('db.lists.get (subject)', err);
		});

	onMount(async () => {
		// console.log('fokusera på input och mata med medhavd data');
		const el = document.getElementById('shortformEl');
		if (el) {
			setTimeout(() => {
				show = true;
				el.focus();
			}, 15);
		}
	});
	const handleKeydown = (e) => {
		if (e.key == 'ArrowDown') {
			if (selectedLists.subject.value > -1) {
				abbForm.target = selectedLists.subject;
			}
		}

		if (e.key == 'ArrowUp') {
			if (selectedLists.standard.value > -1) {
				abbForm.target = selectedLists.standard;
			}
		}
	};
</script>

<div use:clickOutside={cancelCreate}>
	<Card.Root class="mx-auto w-[490px]">
		<Card.Header>
			<Card.Title>Lägg till förkortning</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"
				on:submit={handleCreate}
				autocomplete="off"
			>
				<div role="button" tabindex="-1" on:keydown={handleKeydown} class="grid gap-4">
					<div class="grid grid-cols-4 items-center gap-4">
						<Label>Förkortning</Label>
						<Input
							id="shortformEl"
							bind:value={abbForm.shortform}
							placeholder=""
							class="w-[290px]"
						/>
					</div>
					<div class="grid grid-cols-4 items-center gap-4">
						<Label>Text</Label>
						<Input id="phraseEl" bind:value={abbForm.phrase} placeholder="" class="w-[290px]" />
					</div>
					<div class="grid grid-cols-4 items-center gap-4">
						<Label>Mål</Label>
						<Select.Root selected={abbForm.target} {onSelectedChange}>
							<Select.Trigger class="w-[290px]">
								<Select.Value placeholder="Ingen lista vald" />
							</Select.Trigger>

							<Select.Content>
								{#if selectedLists.standard.value > -1}
									<Select.Group>
										<Select.Label>Standardlista</Select.Label>
										<Select.Item
											value={selectedLists.standard.value}
											label={selectedLists.standard.label}
											>{selectedLists.standard.label}</Select.Item
										>
									</Select.Group>
								{/if}
								{#if selectedLists.subject.value > -1}
									<Select.Group>
										<Select.Label>Ämneslista</Select.Label>
										<Select.Item
											value={selectedLists.subject.value}
											label={selectedLists.subject.label}>{selectedLists.subject.label}</Select.Item
										>
									</Select.Group>
								{/if}
							</Select.Content>
						</Select.Root>
					</div>
				</div>
				<div>
					<small class="text-gray-500 dark:text-gray-400">
						Växla mellan förkortningslistor med <kbd
							class="rounded-lg border border-gray-200 bg-gray-100 px-2 py-1.5 text-xs font-semibold text-gray-800 dark:border-gray-500 dark:bg-gray-600 dark:text-gray-100"
							>Pil upp</kbd
						>
						och
						<kbd
							class="rounded-lg border border-gray-200 bg-gray-100 px-2 py-1.5 text-xs font-semibold text-gray-800 dark:border-gray-500 dark:bg-gray-600 dark:text-gray-100"
							>Pil ned</kbd
						>
					</small>
				</div>
				{#if abbForm.errors.length > 0}
					<ScrollArea class="max-h-48 rounded-md">
						<div
							class="border-l-4 border-orange-500 bg-orange-100 p-4 text-orange-700"
							role="alert"
						>
							<p class="font-bold">Fel vid import</p>
							<ul class="p-6">
								{#each abbForm.errors as error}
									<li class="list-disc">{error}</li>
								{/each}
							</ul>
						</div>
					</ScrollArea>
				{/if}
				<button type="submit" class="hidden" aria-label="submit-button"></button>
			</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>
</div>
