<script>
    import { Button } from "$lib/components/ui/button/index.js";
  	import { Label } from "$lib/components/ui/label/index.js";
    import { Input } from "$lib/components/ui/input/index.js";
    import ReusableCalendar from "$lib/components/reusable/reusable-calendar.svelte";
    import { Spinner } from "$lib/components/ui/spinner/index.js";
    import * as Select from "$lib/components/ui/select/index.js";

    let props = $props();

    let loadedFields = $state(new Set());
</script>

<div class="w-full">
    <div class="w-full space-y-2">
        {#each props.searchFields as field}
            {#if field.type === "text"}
                <div class="space-y-2">
                    <Label for={field.key}>{field.label}</Label>
                    <Input type="text" id={field.key} placeholder={field.placeholder} bind:value={props.searchQuery[field.key]} autocomplete=off/>
                </div>
            {:else if field.type === "date"}
                <div class="space-y-2">
                    <ReusableCalendar title={field.label} bind:value={props.searchQuery[field.key]}/>
                </div>
            {:else if field.type === "select"}
                <div class="w-full space-y-2">
                    <Label for={field.key}>{field.label}</Label>
                    <Select.Root type="single" bind:value={props.searchQuery[field.key]}
                        onOpenChange={() => {
                            props.fetchOptions(field)
                        }}
                    >
                        <Select.Trigger id={field.key} class="w-full flex justify-between">
                            {
                                props.selectOptions[field.key]?.find(
                                    opt => opt.value === props.searchQuery[field.key]
                                )?.label ?? "Choose"
                            }
                        </Select.Trigger>
                        <Select.Content class="w-full">
                            <Select.Item value="">- None -</Select.Item>
                            {#each props.selectOptions[field.key] as opt}
                                <Select.Item value={opt.value}>
                                    {opt.label}
                                </Select.Item>
                            {/each}
                        </Select.Content>
                    </Select.Root>
                </div>
            {/if}
        {/each}
    </div>
    <div class="flex justify-end gap-2 mt-4">
        <Button variant="outline" size="sm" class="cursor-pointer" onclick={props.onReset}>Reset</Button>
        <Button size="sm" class="cursor-pointer" onclick={props.onSearch} disabled={props.isLoading}>
            {#if props.isLoading}
                <Spinner />
            {:else}
                Search
            {/if}
        </Button>
    </div>
</div>