
export default {

    data() {
        return {
            sharedComponents: null,
            group: null,
            filter: '',
            selected: null,

        }
    },

    props: {
        components: {
            type: Object,
            default: {}
        },
        select: {
            type: Function,
        },
        layout: {
            type: Array,
            default: []
        },
        insertPosition: {
            type: Number,
            default: -1
        },
        globalComponents: {
            type: Object,
            default: null
        },
    },

    computed: {

        filtered() {
            let components = [];

            (this.sharedComponents || []).forEach(c => {

                if (this.filter && !c.name.toLocaleLowerCase().includes(this.filter.toLocaleLowerCase())) {
                    return;
                }

                if (this.group && c.component != this.group ) return;
                components.push(c)
            });

            if (components.length) {
                // Sort components by label or name
                components.sort((a, b) => {
                    return (a.name || '').localeCompare(b.name || '');
                });
            }

            return components;
        },

        groups() {
            let groups = [];

            (this.sharedComponents || []).forEach(c => {
                if (!c.component || groups.indexOf(c.component) > -1) return;
                groups.push(c.component);
            });

            return groups.sort();
        },

        selectedComponent() {
            return this.selected !== null ? this.filtered[this.selected] : null;
        }
    },

    mounted() {

        this.$request('/layout-components/shared/load', {options:{}}).then(components => {

            let sharedComponents = [];
            let restrict = Object.keys(this.components);

            components.forEach(c => {
                if (restrict.includes(c.component)) sharedComponents.push(c);
            });

            this.sharedComponents = sharedComponents;

            setTimeout(() => {
                const autofocus = this.$el.parentNode.querySelector('input[autofocus]');
                if (autofocus) autofocus.focus();
            }, 150);
        });
    },

    methods: {

        selectComponent(component) {

            let item = {
                id: App.utils.nanoid(),
                shared: component._id,
                component: component.component,
                label: component.name,
                data: {},
                meta: {}
            };

            if (this.insertPosition > -1) {
                this.layout.splice(this.insertPosition + 1, 0, item);
            } else {
                this.layout.push(item);
            }

            this.select(item);
        },

        keydown(event) {

            switch (event.keyCode) {

                // close on ESC
                case 27:
                    this.selected = null;
                    break;
                // enter
                case 13:

                    if (this.selected !== null) {
                        event.preventDefault();
                        this.select(this.selectedComponent);
                        return;
                    }

                    if (this.filtered.length === 1) {
                        event.preventDefault();
                        this.select(this.filtered[0]);
                        return;
                    }

                    break;

                // up | down
                case 38:
                case 40:

                    const components = this.filtered;

                    if (!components.length) {
                        return;
                    }

                    event.preventDefault();

                    if (this.selected === null) {
                        this.selected = event.keyCode == 38 ? components.length - 1 : 0;
                    } else {

                        if (event.keyCode == 38) {
                            this.selected = components[this.selected - 1] ? this.selected - 1 : components.length - 1 ;
                        } else {
                            this.selected = components[this.selected + 1] ? this.selected + 1 : 0 ;
                        }
                    }

                    const ele = document.getElementById(`layout-component-picker-${this.selectedComponent._id}`);

                    if (ele) {
                        ele.scrollIntoView({behavior: 'smooth', block: 'start'});
                    }
                    break;
            }
        }

    },

    template: /* html */`

        <div class="kiss-padding" :class="{'kiss-disabled': !sharedComponents || !sharedComponents.length}">
            <input type="text" class="kiss-input" :placeholder="t('Filter components...')" @keydown="keydown" @input="selected=null" v-model="filter" autofocus>

            <div class="kiss-flex kiss-margin-small-top kiss-width-1-2@m kiss-overlay-input" gap>
                <div>
                    <div>
                        <span class="kiss-text-caption kiss-color-muted">{{ t('Group') }}</span>
                        <div class="kiss-text-capitalize kiss-size-xsmall" :class="{'kiss-color-muted': !group, 'kiss-text-bold': group}">{{ group || t('All components') }}</div>
                    </div>
                    <select v-model="group" @change="selected=null">
                        <option :value="null">{{ t('All components') }}</option>
                        <option :value="name" v-for="name in groups">{{ name }}</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="app-offcanvas-content kiss-padding">

            <app-loader v-if="!sharedComponents"></app-loader>

            <div class="kiss-flex kiss-flex-center" v-if="sharedComponents && (!sharedComponents.length || !filtered.length)">
                <div class="kiss-color-muted kiss-align-center">
                    <div><kiss-svg :src="$baseUrl('layout:assets/icons/shared.svg')" width="50" height="50"></kiss-svg></div>
                    <div class="kiss-margin-small">{{ t('No shared components') }}</div>
                </div>
            </div>

            <div v-if="sharedComponents && sharedComponents.length">
                <kiss-card :id="'layout-component-picker-'+component._id" class="kiss-padding-small kiss-position-relative kiss-margin-small" theme="bordered" hover="contrast shadow" :style="{borderColor: selected === idx ? 'var(--kiss-color-primary)':''}" v-for="component, idx in filtered">
                    <kiss-row class="kiss-flex-middle" gap="small">
                        <div>
                            <kiss-svg :src="$baseUrl('layout:assets/icons/shared.svg')" width="30" height="30"></kiss-svg>
                        </div>
                        <div class="kiss-size-small kiss-flex-1">
                            <div class="kiss-text-bold kiss-text-truncate">{{ component.name }}</div>
                            <div class="kiss-size-xsmall kiss-color-muted">{{ component.component }}</div>
                        </div>
                    </kiss-row>
                    <a class="kiss-cover" @click="selectComponent(component)" :title="component.name"></a>
                </kiss-card>
            </div>
        </div>
        `
}
