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

export default {

    data() {
        return {
            items: [],
            filter: '',
            group: null,
            globalComponents: null,
            getGroupColor
        }
    },

    mounted() {
        this.load();
        
        App.utils.getlayoutComponents().then(components => {
            this.globalComponents = components;
        });
    },

    computed: {

        filtered() {

            if (!this.items.length) {
                return [];
            }

            return this.items.filter(item => {
                
                if (this.filter && !`${item.label} ${item.component.component}`.toLocaleLowerCase().includes(this.filter.toLocaleLowerCase())) {
                    return false;
                }

                if (this.group) {
                    if (item.component.component != this.group) return false;
                }

                return true;
            });
        },

        groups() {
            let groups = [];

            if (this.globalComponents) {
                this.items.forEach(item => {
                    if (groups.indexOf(item.component.component) === -1) {
                        groups.push(item.component.component);
                    }
                });
            }

            return groups.sort();
        }
    },

    methods: {

        load() {
            let history;
            try {
                history = JSON.parse(App.storage.get('layout.field.clipboard.history', '[]', true));
            } catch (e) {
                history = [];
            }

            if (!Array.isArray(history)) {
                history = [];
            }

            // Ensure each item in history has a 'time' property
            history = history.map(item => {
                if (!item.time) {
                    item.time = Date.now();
                }
                return item;
            });

            this.items = history;

            if (!Array.isArray(this.items)) {
                this.items = [];
            }
        },

        save() {
            App.storage.set('layout.field.clipboard.history', JSON.stringify(this.items));
            
            // Sync with legacy single item storage for backward compatibility
            if (this.items.length) {
                App.storage.set('layout.field.clipboard.component', JSON.stringify(this.items[0].component));
            } else {
                App.storage.set('layout.field.clipboard.component', 'null');
            }
            
            App.trigger('layout.field.clipboard.change', {
                component: this.items.length ? this.items[0].component : null,
                items: this.items
            });
        },

        paste(item) {
            this.$call('paste', item.component);
            this.$close();
        },

        remove(item) {
            const index = this.items.indexOf(item);
            if (index > -1) {
                this.items.splice(index, 1);
                this.save();
            }
        },

        clear() {
            this.items = [];
            this.save();
        }
    },

    template: /*html*/`
        <div class="app-offcanvas-container">
            
            <div class="kiss-padding kiss-flex kiss-flex-middle" gap="small">
                <div>
                    <span class="kiss-size-xsmall kiss-color-muted kiss-text-upper">{{ t('Layout') }}</span>
                    <div class="kiss-size-4 kiss-text-bold">{{ t('Clipboard') }}</div>
                </div>
            </div>

            <div class="kiss-padding" v-if="items.length">
                <input type="text" class="kiss-input" :placeholder="t('Filter components...')" v-model="filter" autofocus>

                <div class="kiss-flex kiss-margin-small-top kiss-width-1-2@m kiss-overlay-input" gap v-if="groups.length">
                    <div>
                        <div>
                            <span class="kiss-text-caption kiss-color-muted">{{ t('Type') }}</span>
                            <div class="kiss-text-capitalize kiss-size-xsmall" :class="{'kiss-color-muted': !group, 'kiss-text-bold': group}">{{ group ? (globalComponents[group] ? (globalComponents[group].label || group) : group) : t('All types') }}</div>
                        </div>
                        <select v-model="group">
                            <option :value="null">{{ t('All types') }}</option>
                            <option :value="name" v-for="name in groups">{{ globalComponents[name] ? (globalComponents[name].label || name) : name }}</option>
                        </select>
                    </div>
                </div>
            </div>

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

                <div class="kiss-color-muted kiss-align-center kiss-padding-large" v-if="!items.length">
                    <icon class="kiss-size-1">content_paste_off</icon>
                    <div class="kiss-margin-small-top">{{ t('Clipboard is empty') }}</div>
                </div>

                <div v-if="items.length">

                    <kiss-card class=" kiss-padding-small kiss-flex kiss-flex-middle kiss-margin-small" theme="bordered" hover="contrast bordered-primary" gap="small" v-for="item in filtered">
                        <div class="kiss-position-relative kiss-flex-1 kiss-margin-right kiss-flex kiss-flex-middle" gap="small">
                            
                            <div v-if="globalComponents && globalComponents[item.component.component]">
                                <kiss-svg :src="$baseUrl(globalComponents[item.component.component].icon)" width="35" height="35" :style="{color: getGroupColor(globalComponents[item.component.component].group)}" v-if="globalComponents[item.component.component].icon"></kiss-svg>
                                <app-avatar size="35" :name="item.component.component" :color="getGroupColor(globalComponents[item.component.component].group)" v-if="!globalComponents[item.component.component].icon"></app-avatar>
                            </div>

                            <div>
                                <div class="kiss-text-bold">{{ item.label || item.component.label || 'Unknown' }}</div>
                                <div class="kiss-size-xsmall kiss-color-muted kiss-text-monospace">
                                    <span class="kiss-text-capitalize">{{ item.component.component }}</span> &mdash; <app-datetime type="relative" :datetime="item.time" />
                                </div>
                            </div>
                            <a class="kiss-cover" @click="paste(item)" :title="t('Paste')"></a>
                        </div>
                        <a class="kiss-color-danger" @click="remove(item)"><icon>delete</icon></a>
                    </kiss-card>
        
                </div>
            </div>

            <div class="kiss-padding">

                <div class="kiss-button-group kiss-flex kiss-flex-end" :class="{'kiss-child-width-1-2': items.length > 0}">
                    <button class="kiss-button kiss-button-danger" @click="clear" v-if="items.length">{{ t('Clear history') }}</button>
                    <button class="kiss-button" kiss-offcanvas-close>{{ items.length ? t('Cancel') : t('Close') }}</button>
                </div>
            </div>
        </div>
    `
}
