{% extends 'django_glue/form/glue_field/base_field.html' %}

{% block field_content %}
    {# This needs to be outside of the child x-data for x-ref to be set correctly #}
    <input
        type="text"
        x-model="value"
        x-ref="glue_field"
        hidden
    >
    <div
        class="position-relative"
        x-data="{
            show_dropdown: false,
            search: '',
            value: '[]',
            init() {
                if (this.glue_field.value) {
                    this.glue_field.value = JSON.stringify(this.glue_field.value);
                    this.value = this.glue_field.value;
                } else {
                    $watch('glue_field', field => {
                        if (field.value) {
                            if (typeof(field.value) == 'object') {
                                this.value = JSON.stringify(field.value);
                            }
                        }
                    });
                }

                // Remove the '---------' option from choices
                this.glue_field.choices = this.glue_field.choices.filter(choice => choice[1] !== '----------');
            },
            add_choice(choice) {
                const selected_values = this.get_selected_values();
                selected_values.push(choice[0]);
                this.update_value(selected_values);
            },
            remove_choice(choice) {
                const selected_values = this.get_selected_values().filter(val => val !== choice[0]);
                this.update_value(selected_values);
            },
            update_value(values) {
                value = JSON.stringify(values);

                this.value = value;
                this.$refs.glue_field.value = value;
            },
            get_selected_values() {
                try {
                    const value = JSON.parse(this.value);
                    return Array.isArray(value) ? value : [value];
                } catch (e) {
                    return [];
                }
            },
            get_selected_choices() {
                const selected_values = this.get_selected_values();
                return this.glue_field.choices.filter(choice => selected_values.includes(choice[0]));
            },
            get filtered_choices() {
                const selected_values = this.get_selected_values();
                const filtered_array = this.glue_field.choices.filter(
                    choice => !selected_values.includes(choice[0])
                );

                const search = this.search.toLowerCase();
                return filtered_array.filter(filtered_choice => filtered_choice[1].toLowerCase().includes(search));
            },
            focus_input() {
                setTimeout(() => this.$refs.search_input.focus(), 100);
            },
        }"
    >
        {% block selected_choices %}
            <button
                class="form-control text-start d-flex justify-content-between"
                type="button"
                @click="show_dropdown = !show_dropdown; focus_input();"
            >
                {#  Display selected choices in dropdown field #}
                <span class="d-flex flex-wrap align-items-center">
                    <template x-for="(choice, index) in get_selected_choices()" :key="index">
                        <div class="d-inline-block my-1">
                            <span class="badge rounded-pill bg-app-glue-secondary-soft glue-fs--1 fw-normal border text-app-glue-black me-1">
                                <span x-text="choice[1]"></span>
                            </span>
                        </div>
                    </template>

                    <template x-if="get_selected_choices().length === 0">
                        <span class="">----------</span>
                    </template>
                </span>

                <span class="d-flex align-items-center">
                    {% include 'django_glue/form/glue_field/element/select_down_arrow_element.html' %}
                </span>
            </button>
        {% endblock %}

        <div
            x-cloak
            x-show="show_dropdown"
            @click.outside="show_dropdown = false"
            class="shadow border rounded-2 border-secondary-subtle mt-2 position-absolute z-3 bg-white w-100 p-0 list-group"
            style="max-height: 350px; overflow-y: auto; z-index: 3;"
            @keydown.escape="show_dropdown = false"
            x-trap.inert="show_dropdown"
        >
            <div class="glue-fs--2 fw-bold ms-2 my-1">
                Select Many <span class="text-muted">"<span x-text="glue_field.label"></span>"</span>
            </div>

            <div class="m-1">
                <input
                    x-model="search"
                    class="form-control py-1 glue-fs--2"
                    placeholder="Search..."
                    type="text"
                    x-ref="search_input"
                    @keydown.enter.prevent="value = filtered_choices[0][0]; show_dropdown = false"
                >
            </div>

            <template x-for="(choice, index) in get_selected_choices()" :key="index">
                <div
                    class="glue-cursor-pointer glue-user-select py-1 d-flex align-items-center list-group-item px-0 bg-app-glue-layer-one-hover"
                    tabindex="0"
                    @click="remove_choice(choice)"
                    @keydown.enter.prevent="remove_choice(choice)"
                >
                    {% block selected_choice_item %}
                        {% include 'django_glue/form/glue_field/item/selected_choice_item.html' %}
                    {% endblock %}
                </div>
            </template>

            <template x-if="get_selected_choices().length > 0 && filtered_choices.length !== 0">
                <div class="bg-app-glue-secondary-soft">
                    <span class="text-muted d-block glue-fs--2 ms-3">Choices</span>
                </div>
            </template>

            {# Loop though available choices  #}
            <template x-for="(choice, index) in filtered_choices" :key="choice[0]">
                <div
                    class="glue-cursor-pointer glue-user-select py-1 d-flex align-items-center list-group-item px-0 bg-app-glue-layer-one-hover"
                    tabindex="0"
                    @click="add_choice(choice)"
                    @keydown.enter.prevent="add_choice(choice)"
                >
                    {% block choice_item %}
                        {% include 'django_glue/form/glue_field/item/select_choice_item.html' %}
                    {% endblock %}
                </div>
            </template>

            {# Message if no available choices #}
            <template x-if="filtered_choices.length === 0">
                <div class="py-1 bg-app-glue-secondary-soft">
                    <span class="text-muted d-block glue-fs--2 ms-3">No available choices</span>
                </div>
            </template>
        </div>
    </div>
{% endblock %}
