<template>
    <v-dialog :model-value="modelValue" :max-width="fileType === 'image' ? '1200' : '900'" scrollable
        @update:model-value="emit('update:modelValue', $event)">
        <v-card>
            <v-toolbar density="compact">
                <v-toolbar-title class="text-subtitle-2 text-truncate">{{ fileName }}</v-toolbar-title>
                <v-spacer />
                <v-btn icon="mdi-open-in-new" variant="text" size="small" @click="openInNewTab()" />
                <v-btn icon="mdi-close" variant="text" size="small" @click="emit('update:modelValue', false)" />
            </v-toolbar>
            <v-card-text class="pa-0"
                :style="{ height: fileType === 'image' ? 'auto' : '75vh', 'overflow-y': fileType === 'image' ? 'auto' : 'auto' }">
                <!-- Image Viewer -->
                <v-img v-if="fileType === 'image'" :src="getFileUrl(fileId)" :alt="fileName" class="w-100" />

                <!-- Video Viewer -->
                <video v-else-if="fileType === 'video'" width="100%" height="100%" controls
                    style="background-color: #000;">
                    <source :src="getFileUrl(fileId)" :type="mimeType" />
                    Your browser does not support the video tag.
                </video>

                <!-- Document Viewer (PDF, Word, etc.) -->
                <iframe v-else :src="getFileUrl(fileId)" width="100%" height="100%" style="border: none;"
                    :title="fileName" />
            </v-card-text>
            <v-card-actions>
                <v-spacer />
                <v-btn variant="text" class="text-none" @click="openInNewTab()">
                    <v-icon start>mdi-download</v-icon>
                    Open / Download
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    fileId: {
        type: String,
        required: true,
    },
    fileName: {
        type: String,
        default: "Document",
    },
    mimeType: {
        type: String,
        default: "application/octet-stream",
    },
});

const emit = defineEmits(['update:modelValue']);

const { getFileUrl } = useFile();

const fileType = computed(() => {
    if (props.mimeType.startsWith('image/')) {
        return 'image';
    } else if (props.mimeType.startsWith('video/')) {
        return 'video';
    } else {
        return 'document';
    }
});

function openInNewTab() {
    window.open(getFileUrl(props.fileId), '_blank', 'noopener,noreferrer');
}
</script>
