<script lang="ts">
    import Select from "svelte-select/Select.svelte"
    import { onMount } from "svelte"
    import type { Writable } from "svelte/store"

    export let options: MultiSelectOptions[] = []
    export let groupTitle: string

    export let formValues: Writable<FormValues>
    export let rowNr: number
    export let formCol: FormColumn

    let valueStorage: any[] = []
    let value: string[] = []
    let values = options.map((option) => ({ label: option.name, value: option.name }))
    let lastCustomInput: string | null = null

    function setFormValues() {
        // @ts-ignore
        $formValues[`selectMultiple_${groupTitle}_${rowNr}_${formCol.multiSelectEmailTitle}`] = {
            value: value.toString(),
            required: !formCol.multiSelectNotRequired,
        }
    }

    function handleInputChange(e: Event) {
        const newCustomInput = (e.target as HTMLInputElement).value

        // Remove the last custom input if it exists
        if (lastCustomInput) {
            values = values.filter((item) => item.label !== lastCustomInput)
        }

        // Add the new custom input
        if (newCustomInput && !values.some((item) => item.label === newCustomInput)) {
            values = [...values, { label: newCustomInput, value: newCustomInput }]
        }

        // Update lastCustomInput
        lastCustomInput = newCustomInput
    }

    $: {
        if (value.length) {
            setFormValues()
        }
    }

    onMount(() => {
        if (typeof window !== "undefined") {
            const inputEl = document.querySelector(".svelte-select input")
            if (inputEl) {
                inputEl.addEventListener("input", handleInputChange)
            }
            return () => {
                if (inputEl) {
                    inputEl.removeEventListener("input", handleInputChange)
                }
            }
        }
    })
    $: if (!valueStorage) {
        valueStorage = []
    }
    $: value = valueStorage.map((item) => item.value)
</script>

<Select
    bind:items="{values}"
    inputAttributes="{{ autocomplete: 'on' }}"
    placeholder=""
    showChevron="{true}"
    clearable="{true}"
    hideEmptyState="{true}"
    searchable="{true}"
    multiple="{true}"
    bind:value="{valueStorage}"
    on:clear="{() => (valueStorage = [])}"
/>

<style lang="less" global>
    @import "../../../assets/css/variables.less";
    @import "../../../assets/css/svelte-select.less";
</style>
