<script setup lang="ts">
import {
    ContextMenu,
    ContextMenuTrigger,
    ContextMenuContent,
    ContextMenuItem,
} from '@/components/ui/context-menu';
import { deleteWarrenDirectory, deleteWarrenFile } from '~/lib/api/warrens';
import type { DirectoryEntry } from '~/types';
import { buttonVariants } from '@/components/ui/button';

const route = useRoute();
const warrenRoute = useWarrenRoute();

const { entry, disabled } = defineProps<{
    entry: DirectoryEntry;
    disabled: boolean;
}>();

const deleting = ref(false);

async function submitDelete(force: boolean = false) {
    deleting.value = true;

    if (entry.fileType === 'directory') {
        await deleteWarrenDirectory(warrenRoute.value, entry.name, force);
    } else {
        await deleteWarrenFile(warrenRoute.value, entry.name);
    }

    deleting.value = false;
}
</script>

<template>
    <ContextMenu>
        <ContextMenuTrigger>
            <NuxtLink
                :to="joinPaths(route.path, entry.name)"
                :class="[
                    'flex flex-row gap-4 bg-accent/30 border-1 border-border px-4 py-2 rounded-md select-none w-52',
                    {
                        'pointer-events-none':
                            disabled || entry.fileType === 'file',
                    },
                ]"
            >
                <div class="flex flex-row items-center">
                    <Icon class="size-6" :name="getFileIcon(entry.mimeType)" />
                </div>

                <div
                    class="flex flex-col gap-0 leading-6 overflow-hidden truncate"
                >
                    <span>{{ entry.name }}</span>
                    <NuxtTime
                        :datetime="entry.createdAt * 1000"
                        class="text-muted-foreground text-sm"
                        relative
                    ></NuxtTime>
                </div>
            </NuxtLink>
        </ContextMenuTrigger>
        <ContextMenuContent>
            <ContextMenuItem @select="() => submitDelete(false)">
                <Icon name="lucide:trash-2" />
                Delete
            </ContextMenuItem>
            <ContextMenuItem
                v-if="entry.fileType === 'directory'"
                @select="() => submitDelete(true)"
            >
                <Icon
                    class="text-destructive-foreground"
                    name="lucide:trash-2"
                />
                Force delete
            </ContextMenuItem>
        </ContextMenuContent>
    </ContextMenu>
</template>
