<template>
    <v-card width="100%" :loading="processing">
        <v-toolbar>
            <v-row no-gutters class="fill-height px-6" align="center">
                <span class="font-weight-bold text-subtitle-1 text-capitalize">
                    Preview Announcement
                </span>
            </v-row>
        </v-toolbar>

        <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0 my-3">
            <v-row no-gutters>
                <template v-for="(label, key) in formattedFields" :key="key">
                    <v-col cols="12" class="mb-5">
                        <v-row no-gutters class="">
                            <v-col class="font-weight-bold">{{ label }}:</v-col>

                            <v-col cols="9" class="px-10">
                                <span v-if="key === 'content'" v-html="getFieldValue(key)" />
                                <span v-else-if="key === 'noExpiration'">
                                    <BulletinExpirationChip :value="getFieldValue(key) as boolean" />
                                </span>
                                <span v-else>
                                    {{ getFieldValue(key) }}
                                </span>
                            </v-col>


                        </v-row>
                    </v-col>
                </template>

                <v-col cols="12" v-if="prop.activeAnnouncement?.file?.length > 0" class="mb-5">
                    <v-row no-gutters>
                        <v-col class="font-weight-bold">Attachments:</v-col>
                        <v-col cols="9" class="px-10">

                            <template v-if="videosArray.length > 0">
                                <div class="text-caption text-medium-emphasis mb-1">Videos ({{ videosArray.length }})</div>
                                <v-list density="compact" class="pa-0 rounded-lg border mb-3">
                                    <template v-for="(item, i) in videosArray" :key="item._id">
                                        <v-divider v-if="i > 0" />
                                        <v-list-item
                                            :prepend-icon="getFileIcon(item.file.type)"
                                            :title="item.file.name"
                                            :subtitle="item.file.type"
                                            class="cursor-pointer"
                                            @click="openMediaViewer(item._id, 'media')"
                                        >
                                            <template #prepend>
                                                <v-icon :color="getFileIconColor(item.file.type)" class="mr-3">{{ getFileIcon(item.file.type) }}</v-icon>
                                            </template>
                                            <template #append>
                                                <v-icon size="16" color="grey-lighten-1">mdi-play-circle-outline</v-icon>
                                            </template>
                                        </v-list-item>
                                    </template>
                                </v-list>
                            </template>

                            <template v-if="photosArray.length > 0">
                                <div class="text-caption text-medium-emphasis mb-1" :class="{ 'mt-3': videosArray.length > 0 }">Photos ({{ photosArray.length }})</div>
                                <v-list density="compact" class="pa-0 rounded-lg border mb-3">
                                    <template v-for="(item, i) in photosArray" :key="item._id">
                                        <v-divider v-if="i > 0" />
                                        <v-list-item
                                            class="cursor-pointer"
                                            @click="openMediaViewer(item._id, 'media')"
                                        >
                                            <template #prepend>
                                                <v-avatar size="36" rounded="sm" class="mr-3">
                                                    <v-img :src="getFileUrl(item._id)" cover>
                                                        <template #error>
                                                            <v-icon color="green" size="20">mdi-image</v-icon>
                                                        </template>
                                                    </v-img>
                                                </v-avatar>
                                            </template>
                                            <v-list-item-title class="text-body-2">{{ item.file.name }}</v-list-item-title>
                                            <v-list-item-subtitle class="text-caption">{{ item.file.type }}</v-list-item-subtitle>
                                            <template #append>
                                                <v-icon size="16" color="grey-lighten-1">mdi-eye-outline</v-icon>
                                            </template>
                                        </v-list-item>
                                    </template>
                                </v-list>
                            </template>

                            <template v-if="filesArray.length > 0">
                                <div class="text-caption text-medium-emphasis mb-1" :class="{ 'mt-3': videosArray.length > 0 || photosArray.length > 0 }">Files ({{ filesArray.length }})</div>
                                <v-list density="compact" class="pa-0 rounded-lg border">
                                    <template v-for="(item, i) in filesArray" :key="item._id">
                                        <v-divider v-if="i > 0" />
                                        <v-list-item
                                            class="cursor-pointer"
                                            @click="openFileViewer(item._id, item.file.name)"
                                        >
                                            <template #prepend>
                                                <v-icon :color="getFileIconColor(item.file.type)" class="mr-3">{{ getFileIcon(item.file.type) }}</v-icon>
                                            </template>
                                            <v-list-item-title class="text-body-2">{{ item.file.name }}</v-list-item-title>
                                            <v-list-item-subtitle class="text-caption">{{ item.file.type }}</v-list-item-subtitle>
                                            <template #append>
                                                <v-icon size="16" color="grey-lighten-1">mdi-open-in-new</v-icon>
                                            </template>
                                        </v-list-item>
                                    </template>
                                </v-list>
                            </template>

                        </v-col>
                    </v-row>
                </v-col>

                <!-- Media Carousel (images + videos) -->
                <ImageCarousel v-model="showCarousel" :active-file-id="activeFileId" :files="carouselFiles" />

                <!-- File Viewer Dialog (PDF, docs, etc.) -->
                <v-dialog v-model="showFileDialog" max-width="900" scrollable>
                    <v-card>
                        <v-toolbar density="compact">
                            <v-toolbar-title class="text-subtitle-2 text-truncate">{{ activeFileName }}</v-toolbar-title>
                            <v-spacer />
                            <v-btn icon="mdi-open-in-new" variant="text" size="small"
                                @click="openInNewTab(activeFileId)" />
                            <v-btn icon="mdi-close" variant="text" size="small"
                                @click="showFileDialog = false" />
                        </v-toolbar>
                        <v-card-text class="pa-0" style="height: 75vh;">
                            <iframe
                                :src="getFileUrl(activeFileId)"
                                width="100%"
                                height="100%"
                                style="border: none;"
                                :title="activeFileName"
                            />
                        </v-card-text>
                        <v-card-actions>
                            <v-spacer />
                            <v-btn variant="text" class="text-none" @click="openInNewTab(activeFileId)">
                                <v-icon start>mdi-download</v-icon>
                                Open / Download
                            </v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-row>
        </v-card-text>

        <v-toolbar class="pa-0" density="compact">
            <v-row no-gutters>
                <v-col :col="(!canUpdate && !canDelete) ? 12 : 6" class="pa-0">
                    <v-btn block variant="text" height="48" class="text-none" @click="emit('close')">
                        Close
                    </v-btn>
                </v-col>

                <v-col v-if="canUpdate || canDelete" cols="6" class="pa-0">
                    <v-menu contained>
                        <template #activator="{ props }">
                            <v-btn block variant="flat" color="black" height="48" class="text-none" tile v-bind="props">
                                More actions
                            </v-btn>
                        </template>

                        <v-list class="pa-0">
                            <v-list-item v-if="canUpdate" @click="handleEdit">
                                <v-list-item-title class="text-subtitle-2">
                                    Edit Announcement
                                </v-list-item-title>
                            </v-list-item>

                            <v-list-item v-if="canDelete" class="text-red" @click="handleDelete">
                                <v-list-item-title class="text-subtitle-2">
                                    Delete Announcement
                                </v-list-item-title>
                            </v-list-item>
                        </v-list>
                    </v-menu>
                </v-col>
            </v-row>
        </v-toolbar>
    </v-card>
</template>


<script setup lang="ts">

const prop = defineProps({
    activeAnnouncement: {
        type: Object as PropType<TAnnouncement>,
        required: true
    },
    canUpdate: Boolean,
    canDelete: Boolean,
})

const processing = ref(false)
const { recipientList } = useBulletin()
const { getFileUrl, urlToFile } = useFile()

const emit = defineEmits(['close', 'edit', 'delete'])

/* Field labels */
const formattedFields: Partial<Record<keyof TAnnouncement, string>> = {
    title: "Title",
    createdAt: "Date Created",
    recipients: "Recipients",
    content: "Content",
    startDate: "Start Date",
    endDate: "End Date",
    noExpiration: "No Expiration",
}

const formattedRecipients = computed(() => {
    const arr = recipientList.filter(x =>
        prop.activeAnnouncement?.recipients?.includes(x.value)
    )
    return arr.map(item => item.title).join(", ")
})

function getFieldValue(key: keyof TAnnouncement) {
    const value = prop.activeAnnouncement?.[key]

    if (value === null || value === "" || value === undefined) return ""

    switch (key) {
        case "recipients":
            return formattedRecipients.value
        case "createdAt":
        case "startDate":
        case "endDate":
            return toLocalDate(value as string)
        default:
            return value
    }
}

const rawFileArray = ref<{ file: File, _id: string, preview: boolean }[]>([])

const photosArray = getByType('image/')
const videosArray = getByType('video/')
const filesArray = getByType('other')

/* Viewer state */
const showCarousel = ref(false)
const showFileDialog = ref(false)
const activeFileId = ref('')
const activeFileName = ref('')
const carouselFiles = ref<string[]>([])

function openMediaViewer(id: string, _type: 'media') {
    activeFileId.value = id
    carouselFiles.value = [
        ...photosArray.value.map(x => x._id),
        ...videosArray.value.map(x => x._id),
    ]
    showCarousel.value = true
}

function openFileViewer(id: string, name: string) {
    activeFileId.value = id
    activeFileName.value = name
    showFileDialog.value = true
}

function openInNewTab(id: string) {
    window.open(getFileUrl(id), '_blank', 'noopener,noreferrer')
}

function getFileIcon(mimeType: string): string {
    if (mimeType.startsWith('image/')) return 'mdi-image'
    if (mimeType.startsWith('video/')) return 'mdi-video'
    if (mimeType === 'application/pdf') return 'mdi-file-pdf-box'
    if (mimeType.includes('word') || mimeType.includes('document')) return 'mdi-file-word-box'
    if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return 'mdi-file-excel-box'
    if (mimeType.includes('powerpoint') || mimeType.includes('presentation')) return 'mdi-file-powerpoint-box'
    if (mimeType === 'text/plain') return 'mdi-file-document-outline'
    if (mimeType.includes('zip') || mimeType.includes('compressed') || mimeType.includes('archive')) return 'mdi-folder-zip-outline'
    return 'mdi-file-outline'
}

function getFileIconColor(mimeType: string): string {
    if (mimeType === 'application/pdf') return 'red'
    if (mimeType.includes('word') || mimeType.includes('document')) return 'blue'
    if (mimeType.includes('excel') || mimeType.includes('spreadsheet')) return 'green'
    if (mimeType.includes('powerpoint') || mimeType.includes('presentation')) return 'orange'
    if (mimeType.startsWith('video/')) return 'purple'
    return 'grey'
}

function getByType(prefix: 'image/' | 'video/' | 'other') {
    return computed(() => {
        return rawFileArray.value.filter(x => {
            const type = x?.file?.type
            if (typeof type !== 'string') return false

            if (prefix === 'other') {
                return !type.startsWith('image/') && !type.startsWith('video/')
            }
            return type.startsWith(prefix)
        })
    })
}

function toLocalDate(utcString: string) {
    if (typeof utcString !== 'string') return;
    return new Date(utcString).toLocaleString("en-US", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
    })
}

function handleEdit() {
    emit("edit")
}

function handleDelete() {
    emit("delete")
}

watchEffect(async () => {
    const data = prop.activeAnnouncement
    if (!data) return

    rawFileArray.value = await Promise.all(
        data.file.map(async (item) => {
            const fileUrl = getFileUrl(item._id)
            const file = await urlToFile(fileUrl, item.name)
            return { file, _id: item._id, preview: item.preview ?? false }
        })
    )
})


</script>
