<template>
    <ui-card :class="{
        'space-y-8': folders.length || assets.length || creatingFolder,
        '!p-0': folders.length === 0 && assets.length === 0 && !creatingFolder
    }">
        <!-- Folders -->
        <section class="folder-grid-listing" v-if="folders.length || creatingFolder">
            <div
                v-if="!restrictFolderNavigation"
                v-for="folder in folders"
                :key="folder.path"
                class="group/folder relative p-1"
                :class="{ 'rounded-xl ring-2 ring-blue-400': dragOverFolder === folder.path }"
                :draggable="true"
                @dragover.prevent="dragOverFolder = folder.path"
                @dragleave.prevent="dragOverFolder = null"
                @drop="
                    handleFolderDrop(folder);
                    dragOverFolder = null;
                "
                @dragstart="draggingFolder = folder.path"
                @dragend="
                    draggingFolder = null;
                    dragOverFolder = null;
                "
            >
                <ItemActions
                    :url="folderActionUrl"
                    :actions="folderActions(folder)"
                    :item="folder.path"
                    @started="actionStarted"
                    @completed="actionCompleted"
                    v-slot="{ actions }"
                >
                    <Context>
                        <template #trigger>
                            <button @click="selectFolder(folder.path)" class="group h-[66px] w-[80px]">
                                <FolderSvg class="size-full text-blue-400/90 hover:text-blue-400" />
                                <div
                                    class="overflow-hidden mt-2 text-center text-xs text-ellipsis whitespace-nowrap text-gray-500 dark:text-gray-300"
                                    v-text="folder.basename"
                                    :title="folder.basename"
                                />
                            </button>
                        </template>
                        <ContextMenu>
                            <ContextItem
                                v-for="action in actions"
                                :key="action.handle"
                                :text="__(action.title)"
                                :icon="action.icon"
                                :variant="action.dangerous ? 'destructive' : 'default'"
                                @click="action.run"
                            />
                        </ContextMenu>
                    </Context>
                </ItemActions>
            </div>
            <div v-if="creatingFolder" class="group/folder relative p-1">
                <div class="group h-[66px] w-[80px]">
                    <FolderSvg class="size-full text-blue-400/90 hover:text-blue-400" />

                    <Editable
                        ref="newFolderInput"
                        v-model:modelValue="newFolderName"
                        :start-with-edit-mode="true"
                        submit-mode="enter"
                        :placeholder="__('Name')"
                        :class="[
                            'flex w-[80px] items-center placeholder:lowercase justify-center overflow-hidden mt-2 text-center text-xs text-ellipsis whitespace-nowrap placeholder:text-gray-400 dark:placeholder:text-gray-500 text-gray-500',
                            { 'st-has-error': creatingFolderError }
                        ]"
                        @submit="$emit('create-folder', newFolderName)"
                        @cancel="
                            () => {
                                newFolderName = null;
                                $emit('cancel-creating-folder');
                            }
                        "
                    />
                </div>
            </div>
        </section>

        <!-- Assets -->
        <section class="asset-grid-listing" v-if="assets.length" :style="{ gridTemplateColumns: gridSize }">
            <div
                v-for="(asset, index) in assets"
                :key="asset.id"
                class="group relative"
                :class="{ selected: isSelected(asset.id) }"
            >
                <ItemActions
                    :url="actionUrl"
                    :actions="asset.actions"
                    :item="asset.id"
                    @started="actionStarted"
                    @completed="actionCompleted"
                    v-slot="{ actions }"
                >
                    <Context>
                        <template #trigger>
                            <div
                                class="asset-tile group relative bg-white dark:bg-gray-900"
                                :class="{
                                    'bg-checkerboard!': asset.can_be_transparent,
                                    'opacity-50!': draggingAsset === asset.id,
                                }"
                            >
                                <button
                                    class="size-full"
                                    :draggable="true"
                                    @dragover.prevent
                                    @dragstart="draggingAsset = asset.id"
                                    @dragend="draggingAsset = null"
                                    @click.stop="selectionClicked(index, $event)"
                                    @dblclick.stop="$emit('edit-asset', asset)"
                                >
                                    <div class="relative flex aspect-square size-full items-center justify-center">
                                        <div class="asset-thumb">
                                            <img
                                                v-if="asset.thumbnail"
                                                :src="asset.thumbnail"
                                                loading="lazy"
                                                :draggable="false"
                                                :class="{
                                                    'w-full p-4': asset.extension === 'svg',
                                                    'rounded-lg p-1': asset.orientation === 'square',
                                                }"
                                            />
                                            <file-icon v-else :extension="asset.extension" class="size-1/2" />
                                        </div>
                                    </div>
                                </button>
                                <div class="absolute end-1 top-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity [&_button]:bg-white [&_button]:hover:bg-white [&_button]:dark:bg-gray-900 [&_button]:dark:hover:bg-gray-900">
                                    <Dropdown placement="left-start">
                                        <DropdownMenu>
                                            <DropdownItem
                                                :text="__(asset.editable ? 'Edit' : 'View')"
                                                @click="edit(asset.id)"
                                                icon="edit"
                                            />
                                            <DropdownSeparator v-if="asset.actions.length" />
                                            <DropdownItem
                                                v-for="action in actions"
                                                :key="action.handle"
                                                :text="__(action.title)"
                                                :icon="action.icon"
                                                :variant="action.dangerous ? 'destructive' : 'default'"
                                                @click="action.run"
                                            />
                                        </DropdownMenu>
                                    </Dropdown>
                                </div>
                            </div>
                        </template>
                        <ContextMenu>
                            <ContextItem icon="edit" :text="__(asset.editable ? 'Edit' : 'View')" @click="edit(asset.id)" />
                            <ContextSeparator />
                            <ContextItem
                                v-for="action in actions"
                                :key="action.handle"
                                :text="__(action.title)"
                                :icon="action.icon"
                                :variant="action.dangerous ? 'destructive' : 'default'"
                                @click="action.run"
                            />
                        </ContextMenu>
                    </Context>
                </ItemActions>
                <div class="asset-filename">
                    <MiddleEllipsis :text="asset.basename" />
                </div>
            </div>
        </section>

        <!-- Empty state -->
        <div v-if="folders.length === 0 && assets.length === 0 && !creatingFolder" class="text-center text-gray-500 text-sm py-4">
            {{ __('No items found') }}
        </div>
    </ui-card>
</template>

<script>
import AssetBrowserMixin from './AssetBrowserMixin';
import Breadcrumbs from './Breadcrumbs.vue';
import {
    Context,
    ContextMenu,
    ContextItem,
    ContextLabel,
    ContextSeparator,
    Editable,
    Dropdown,
    DropdownMenu,
    DropdownLabel,
    DropdownItem,
    DropdownSeparator,
    MiddleEllipsis
} from '@ui';
import { injectListingContext } from '@/components/ui/Listing/Listing.vue';
import ItemActions from '@/components/actions/ItemActions.vue';
import FolderSvg from '@/../svg/folder.svg';

export default {
    mixins: [AssetBrowserMixin],

    components: {
        Breadcrumbs,
        ContextItem,
        ContextLabel,
        ContextMenu,
        ContextSeparator,
        Context,
        Editable,
        Dropdown,
        DropdownMenu,
        DropdownLabel,
        DropdownItem,
        DropdownSeparator,
        ItemActions,
        FolderSvg,
        MiddleEllipsis,
    },

    props: {
        assets: { type: Array },
        selectedAssets: { type: Array },
        thumbnailSize: { type: Number },
    },

    data() {
        return {
            dragOverFolder: null,
            shifting: false,
        };
    },

    computed: {
        gridSize() {
            return `repeat(auto-fill, minmax(${this.thumbnailSize}px, 1fr))`;
        },
    },

    setup() {
        const { selectionClicked } = injectListingContext();

        return { selectionClicked };
    },

    methods: {
        isSelected(id) {
            return this.selectedAssets.includes(id);
        },
    },
};
</script>
