import {generateNewComponentIds} from './../utils.js';

export default {

    data() {
        return {
            templates: 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 templates = [];

            (this.templates || []).forEach(t => {

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

                if (this.group && t.component != this.group ) return;
                templates.push(t)
            });

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

            return templates;
        },

        groups() {
            let groups = [];

            (this.templates || []).forEach(t => {
                if (!t.group || groups.indexOf(t.group) > -1) return;
                groups.push(t.group);
            });

            return groups.sort();
        },

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

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

            this.templates = templates;

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

    methods: {

        selectTemplate(template) {

            let layout = Array.isArray(template.layout) ? template.layout : [];
            let pos = this.insertPosition;

            layout.forEach(item => {

                item = JSON.parse(JSON.stringify(item));
                item = generateNewComponentIds(item);

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

            });

            this.select();

        },

        keydown(event) {

            switch (event.keyCode) {

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

                    if (this.selected !== null) {
                        event.preventDefault();
                        this.selectTemplate(this.selectedTemplate);
                        return;
                    }

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

                    break;

                // up | down
                case 38:
                case 40:

                    const templates = this.filtered;

                    if (!templates.length) {
                        return;
                    }

                    event.preventDefault();

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

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

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

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

    },

    template: /* html */`

        <div class="kiss-padding" :class="{'kiss-disabled': !templates || !templates.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 templates') }}</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="!templates"></app-loader>

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

            <div v-if="templates && templates.length">
                <kiss-card :id="'layout-component-picker-'+tpl._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="tpl, idx in filtered">
                    <kiss-row class="kiss-flex-middle" gap="small">
                        <div>
                            <kiss-svg :src="$baseUrl('layout:icon.svg')" width="30" height="30"></kiss-svg>
                        </div>
                        <div class="kiss-size-small kiss-flex-1">
                            <div class="kiss-text-bold kiss-text-truncate">{{ tpl.name }}</div>
                            <div class="kiss-size-xsmall kiss-color-muted" v-if="tpl.info">{{ tpl.info }}</div>
                        </div>
                    </kiss-row>
                    <a class="kiss-cover" @click="selectTemplate(tpl)" :title="tpl.name"></a>
                </kiss-card>
            </div>
        </div>
        `
}
