<template>
    <div>
        <nav class="siteMenuAdmin__breadcrumbs" v-if="breadcrumbs.length">
            <template v-for="(crumb, i) in breadcrumbs">
                <a v-if="i < breadcrumbs.length - 1" :key="'c' + crumb.id" href="#"
                   @click.prevent="$emit('drill', crumb.id)">{{ crumb.name }}</a>
                <span v-else :key="'c' + crumb.id">{{ crumb.name }}</span>
                <span v-if="i < breadcrumbs.length - 1" :key="'s' + crumb.id" class="siteMenuAdmin__crumbSep">/</span>
            </template>
        </nav>

        <div class="siteMenuAdmin__toolbar">
            <a class="siteMenuAdmin__btn siteMenuAdmin__btn--primary" href="#"
               @click.prevent="$emit('add', current ? current.id : null)">
                <i class="fa fa-plus"></i> Add menu item
            </a>
        </div>

        <div v-if="loading" class="siteMenuAdmin__loading"><i class="fa fa-spinner fa-spin"></i> Loading…</div>

        <div v-else-if="items.length" class="siteMenuAdmin__card">
            <table class="siteMenuAdmin__table">
                <thead>
                    <tr>
                        <th class="siteMenuAdmin__col-order">Order</th>
                        <th class="siteMenuAdmin__col-id">ID</th>
                        <th>Name</th>
                        <th>Sub items</th>
                        <th class="siteMenuAdmin__col-status">Status</th>
                        <th class="siteMenuAdmin__col-actions">Actions</th>
                    </tr>
                </thead>
                <draggable v-model="items" tag="tbody" handle=".siteMenuAdmin__drag"
                           ghost-class="siteMenuAdmin__rowGhost" @end="persistOrder">
                    <tr v-for="item in items" :key="item.id">
                        <td class="siteMenuAdmin__drag" title="Drag to reorder"><i class="fa fa-arrows"></i></td>
                        <td class="siteMenuAdmin__col-id">
                            <a class="siteMenuAdmin__idBadge" href="#" @click.prevent="$emit('edit', item.id)">{{ item.id }}</a>
                        </td>
                        <td>
                            <a class="siteMenuAdmin__name" href="#" @click.prevent="$emit('edit', item.id)">{{ item.name }}</a>
                        </td>
                        <td>
                            <a class="siteMenuAdmin__subLink" href="#" @click.prevent="$emit('drill', item.id)">
                                <i class="fa fa-sitemap"></i> View sub-items
                                <span class="siteMenuAdmin__count">{{ item.child_count }}</span>
                            </a>
                            <ul v-if="item.children_preview && item.children_preview.length" class="siteMenuAdmin__subList">
                                <li v-for="(name, idx) in item.children_preview" :key="idx">{{ name }}</li>
                                <li v-if="item.child_count > item.children_preview.length" class="siteMenuAdmin__subMore">
                                    +{{ item.child_count - item.children_preview.length }} more
                                </li>
                            </ul>
                            <span v-else class="siteMenuAdmin__empty">Empty</span>
                        </td>
                        <td class="siteMenuAdmin__col-status">
                            <site-menu-status :base="base" :item-id="item.id" :published="item.published"></site-menu-status>
                        </td>
                        <td class="siteMenuAdmin__col-actions">
                            <site-menu-actions :base="base" :item-id="item.id" :name="item.name"
                                               @edit="$emit('edit', $event)" @deleted="onDeleted" @duplicated="fetchItems"></site-menu-actions>
                        </td>
                    </tr>
                </draggable>
            </table>
        </div>

        <div v-else class="siteMenuAdmin__card siteMenuAdmin__empty-state">
            <i class="fa fa-sitemap"></i>
            <p>There are no menu items here yet.</p>
            <a class="siteMenuAdmin__btn siteMenuAdmin__btn--primary" href="#"
               @click.prevent="$emit('add', current ? current.id : null)">
                <i class="fa fa-plus"></i> Add your first menu item
            </a>
        </div>
    </div>
</template>

<script>
import draggable from 'vuedraggable';

/**
 * Manage view: lists a menu level from the JSON API, supports drill-in via
 * breadcrumbs / "View sub-items", drag-reorder (vuedraggable -> /api/reorder),
 * and reactive publish/delete/duplicate through child components.
 */
export default {
    name: 'site-menu-list',
    components: { draggable },
    props: {
        base: { type: String, required: true },
        csrf: { type: String, default: '' },
        parentId: { type: [String, Number], default: null },
    },
    data() {
        return { loading: true, current: null, breadcrumbs: [], items: [] };
    },
    watch: {
        parentId() { this.fetchItems(); },
    },
    mounted() {
        this.fetchItems();
    },
    methods: {
        fetchItems() {
            this.loading = true;
            const url = this.base + '/api/items' + (this.parentId ? '?parent_id=' + this.parentId : '');
            fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
                .then(response => response.json())
                .then(data => {
                    this.current = data.current;
                    this.breadcrumbs = data.breadcrumbs || [];
                    this.items = data.items || [];
                })
                .catch(() => {})
                .finally(() => { this.loading = false; });
        },
        onDeleted(id) {
            this.items = this.items.filter(item => item.id !== id);
        },
        persistOrder() {
            const body = new FormData();
            body.append('_token', this.csrf);
            this.items.forEach(item => body.append('order[]', item.id));
            fetch(this.base + '/api/reorder', {
                method: 'POST',
                headers: { Accept: 'application/json' },
                credentials: 'same-origin',
                body,
            }).catch(() => {});
        },
    },
};
</script>
