<script lang="ts">
	import { getZodBaseType } from "#client/lib/helpers.js";
import { filterAusweise } from "#lib/filters.js";
	import { ZodTypeAny } from "astro:schema";
	import { Cross1 } from "radix-svelte-icons";
	import z, { ZodBoolean, ZodNativeEnum, ZodNumber } from "zod"

	export let filters: { name: keyof z.infer<typeof filterAusweise>, type: ZodTypeAny, value: any }[] = []
</script>

{#each filters as filter, i}
	{@const type = getZodBaseType(filter.type)}
	<div class="flex flex-row bg-white gap-4 px-2 py-2 rounded-lg">
		{#if i === 0}
			<span class="badge">where</span>
		{:else}
			<span class="badge">and</span>
		{/if}
		<select on:change={function(e) {
			delete filters[filter.name]
			filter.name = e.target.value;
			filter.type = filterAusweise._def.shape()[filter.name]
			filters = filters.filter(Boolean);
		}}>
		<option value={filter.name} selected>{filter.name}</option>
			{#each Object.keys(filterAusweise._def.shape()) as n}
					{#if !filters.find(filter => filter.name === n)}
						<option value={n}>{n}</option>
					{/if}
			{/each}
		</select>
		<span class="badge">equals</span>
		{#if type instanceof ZodNumber}
			<input type="number" bind:value={filter.value}>
		{:else if type instanceof ZodBoolean}
			<select bind:value={filter.value}>
				<option value={true}>true</option>
				<option value={false}>false</option>
			</select>
		{:else if type instanceof ZodNativeEnum}
			<select bind:value={filter.value}>
				{#each Object.entries(type._def.values) as [key, value]}
					<option {value}>{key}</option>
				{/each}
			</select>
		{:else}
			<input type="text" bind:value={filter.value}>
		{/if}
		<Cross1 size={24} class="cursor-pointer"></Cross1>
	</div>
{/each}

<button on:click={() => {
	const entry = Object.entries(filterAusweise._def.shape())[0]
	filters.push({
		name: entry[0],
		type: entry[1],
		value: null
	})
	filters = filters
}}>Filter Hinzufügen</button>


<style>
	.badge {
		@apply rounded-lg px-2 py-1 bg-gray-500 text-white;
	}
</style>