<template>
    <BaseLayout>
        <main class="content">
            <div class="container-fluid p-0">
                <h1 class="h3 mb-3">Inventory Own & Friends"</h1>
                <div class="row">
                    <div class="col-12 col-xl-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">{{ user }}'s Inventory</h5>
                                <button v-if="layout === 'grid'" @click="layout = 'table'" class="btn">
                                    <b-icon-list></b-icon-list>
                                </button>
                                <button v-else @click="layout = 'grid'" class="btn">
                                    <b-icon-grid></b-icon-grid>
                                </button>
                            </div>
                            <table class="table table-striped" v-if="layout === 'table'">
                                <thead>
                                <tr>
                                    <th style="width:40%;">Name</th>
                                    <th style="width:25%">Availability Policy</th>
                                    <th class="d-none d-md-table-cell" style="width:25%">Amount</th>
                                    <th>Actions</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr v-for="item in inventory_items" :key="item.id">
                                    <td>
                                        <router-link :to="itemRoute(item)">{{ item.name }}</router-link>
                                    </td>
                                    <td class="d-none d-md-table-cell">
                                        <span class="badge bg-secondary text-white">{{ item.availability_policy }}</span>
                                    </td>
                                    <td class="d-none d-md-table-cell">{{ item.owned_quantity }}</td>
                                    <td class="table-action">
                                        <router-link :to="`${itemRoute(item)}/edit`">
                                            <b-icon-pencil-square></b-icon-pencil-square>
                                        </router-link>
                                        <a :href="`${itemRoute(item)}/delete`" @click.prevent="deleteInventoryItem(item)">
                                            <b-icon-trash></b-icon-trash>
                                        </a>
                                        <router-link v-if="shortIdLink(item)" :to="shortIdLink(item)">
                                            <b-icon-link></b-icon-link>
                                        </router-link>
                                        <router-link v-if="printLinkFor(item)" :to="printLinkFor(item)">
                                            <b-icon-qr-code></b-icon-qr-code>
                                        </router-link>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                            <div class="card-body" v-else>
                                <div class="row">
                                    <div class="col-12 col-md-4 col-lg-3 col-xl-2" v-for="item in inventory_items"
                                         :key="item.id">
                                        <div class="card">
                                            <img :src="item.image" class="" :alt="item.image">
                                            <authenticated-image v-if="only_images(item.files).length > 0"
                                                                 :src="only_images(item.files)[0].name"
                                                                 :owner="only_images(item.files)[0].owner"
                                                                 class="card-img-top img-preview"/>
                                            <div class="card-body">
                                                <h5 class="card-title mb-0">
                                                    <router-link :to="itemRoute(item)">
                                                        {{ item.name }}
                                                    </router-link></h5>
                                                <div class="card-text text-black-50">
                                                    <span class="badge bg-secondary text-white">{{ item.availability_policy }}</span>
                                                    <span class="float-right">{{ item.owned_quantity }}</span>
                                                </div>
                                                <div class="btn-group">
                                                    <button class="btn btn-danger btn-sm"
                                                            @click="deleteInventoryItem(item)">Delete
                                                    </button>
                                                    <router-link :to="`${itemRoute(item)}/edit`"
                                                                 class="btn btn-primary btn-sm">Edit
                                                    </router-link>
                                                    <router-link v-if="shortIdLink(item)" :to="shortIdLink(item)"
                                                                 class="btn btn-secondary btn-sm">
                                                        <b-icon-link></b-icon-link>
                                                    </router-link>
                                                    <router-link v-if="printLinkFor(item)" :to="printLinkFor(item)"
                                                                 class="btn btn-secondary btn-sm">
                                                        <b-icon-qr-code></b-icon-qr-code>
                                                    </router-link>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                        <div class="card">
                            <button class="btn" @click="fetchInventoryItems">Refresh</button>
                            <router-link to="/inventory/new" class="btn btn-primary">Add</router-link>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </BaseLayout>
</template>

<script>
import {mapActions, mapGetters, mapMutations, mapState} from "vuex";
import * as BIcons from "bootstrap-icons-vue";
import BaseLayout from "@/components/BaseLayout.vue";
import AuthenticatedImage from "../components/AuthenticatedImage.vue";
import {shortenedRoute, encodeHandleForUrl} from "@/router";

export default {
    name: "Inventory",
    data() {
        return {
            layout: "grid",
        }
    },
    components: {
        AuthenticatedImage,
        BaseLayout,
        ...BIcons
    },
    computed: {
        ...mapGetters(["inventory_items", "loaded_items", "identityIdByHandle", "groupIdByHandle"]),
        ...mapState(["user", "storage_locations"]),
    },
    methods: {
        ...mapActions(["fetchInventoryItems", "deleteInventoryItem", "fetchStorageLocations", "fetchIdMap"]),
        // Always the viewer's own items (fetchInventoryItems has no group filter); the owner
        // handle is always included so /inventory/:handle/:id has exactly one shape.
        itemRoute(item) {
            return `/inventory/${encodeHandleForUrl(this.user)}/${item.id}`
        },
        only_images(files) {
            return files.filter(file => file.mime_type.startsWith("image/"));
        },
        locationPath(item) {
            const loc = this.storage_locations.find(loc => loc.id === item.storage_location)
            return loc ? loc.path : null
        },
        shortIdLink(item) {
            if (item.owner_group) {
                const owner_group_id = this.groupIdByHandle[item.owner_group]
                if (owner_group_id === undefined) return null
                return shortenedRoute({kind: 'group_item', owner_group_id, item_local_id: item.id})
            }
            const owner_identity_id = this.identityIdByHandle[item.owner]
            if (owner_identity_id === undefined) return null
            return shortenedRoute({kind: 'item', owner_identity_id, item_local_id: item.id})
        },
        // Routes to Print.vue with this item's raw identity rather than a pre-built link.
        // See docs/implementation.md#print-link-shape-for-personal-items.
        printLinkFor(item) {
            if (!item.owner) return null
            return {path: '/print', query: {kind: 'item', userHandle: item.owner, item: item.id}}
        },
    },
    async mounted() {
        await this.fetchInventoryItems()
        await this.fetchStorageLocations()
        await this.fetchIdMap()
    }
}
</script>

<style scoped>
.img-preview {
    object-fit: cover;
}
</style>