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

    export let options: { name: string }[] = []
    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?.multiSelectInput?.standardInputProperties?.notRequired,
        }
    }

    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";
    .svelte-select {
        height: 55px !important;
        margin-bottom: 20px;

        margin: 5px 0px !important;
        box-shadow: 0 0 25px 10px rgba(0, 0, 0, 0.05) !important;
        padding: 10px 20px !important;
        border: 0px solid black !important;
        border-bottom: 3px solid @main-color !important;
        outline: 0px solid black !important;
        color: black !important;
        background-color: @background-color !important;
        resize: none !important;
        .value-container {
            input {
                padding-top: 20px;
            }
            .selected-item {
                padding-top: 19px;
            }
        }

        .multi-item {
            background-color: rgba(0, 0, 0, 0.1) !important;
            border-radius: 3px !important;
        }

        .selected-item {
            margin-left: 3px;
            height: auto;
            line-height: initial;
        }
        &.focused {
            border-color: black !important;
        }

        input {
            height: 100%;
            font-size: 1rem !important;
        }

        .list-item {
            .item {
                &.active {
                    background-color: transparent !important;
                    color: black !important;
                }
            }
        }

        .indicators {
            color: #ccc;

            & > * {
                border-left: 1px solid #ccc !important;
                height: 40px !important;
                cursor: pointer !important;
            }

            .clear-select {
                color: @hover-color !important;
                font-weight: 700 !important;
            }
        }
    }
</style>
