<template>
    <Teleport to="body">
        <Transition name="fade" appear>
            <div
                v-if="entry"
                class="fixed inset-0 z-[60] flex items-center justify-center bg-black/80"
                @click.self="$emit('close')"
                @keydown.escape="$emit('close')"
                @keydown.left="$emit('prev')"
                @keydown.right="$emit('next')"
                tabindex="0"
                ref="overlayRef"
            >
                <!-- Close button -->
                <MalioButtonIcon
                    icon="heroicons:x-mark"
                    aria-label="Fermer"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute right-4 top-4 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('close')"
                />

                <!-- Navigation arrows -->
                <MalioButtonIcon
                    v-if="hasPrev"
                    icon="heroicons:chevron-left"
                    aria-label="Précédent"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('prev')"
                />
                <MalioButtonIcon
                    v-if="hasNext"
                    icon="heroicons:chevron-right"
                    aria-label="Suivant"
                    variant="ghost"
                    icon-size="24"
                    button-class="absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 text-white hover:bg-black/70"
                    @click="$emit('next')"
                />

                <!-- Content -->
                <div class="flex max-h-[90vh] max-w-[90vw] flex-col items-center">
                    <!-- Image preview -->
                    <img
                        v-if="isImage"
                        :src="inlineUrl"
                        :alt="entry.name"
                        class="max-h-[85vh] max-w-[90vw] object-contain"
                    />

                    <!-- PDF preview — iframe pattern, même approche que TaskDocumentPreview -->
                    <iframe
                        v-else-if="isPdf"
                        :src="inlineUrl"
                        class="h-[85vh] w-[80vw] rounded-lg bg-white"
                    />

                    <!-- Text / Markdown / JSON / XML / CSV / Log preview -->
                    <div
                        v-else-if="isText"
                        class="flex max-h-[85vh] w-[85vw] max-w-3xl flex-col overflow-hidden rounded-xl bg-white"
                    >
                        <div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
                            <p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
                            <a
                                :href="downloadUrl"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                            >
                                {{ $t('sharedFiles.download') }}
                            </a>
                        </div>
                        <div class="overflow-auto p-4">
                            <div v-if="loadingText" class="flex justify-center py-10">
                                <Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
                            </div>
                            <pre
                                v-else
                                class="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-neutral-800"
                            >{{ textContent }}</pre>
                        </div>
                    </div>

                    <!-- DOCX preview — rendu HTML via docx-preview (lazy) -->
                    <div
                        v-else-if="isDocx"
                        class="flex max-h-[85vh] w-[85vw] max-w-4xl flex-col overflow-hidden rounded-xl bg-white"
                    >
                        <div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
                            <p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
                            <a
                                :href="downloadUrl"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                            >
                                {{ $t('sharedFiles.download') }}
                            </a>
                        </div>
                        <div class="overflow-auto bg-neutral-100 p-4">
                            <div v-if="loadingOffice" class="flex justify-center py-10">
                                <Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
                            </div>
                            <p v-else-if="officeError" class="py-10 text-center text-sm text-red-600">
                                {{ $t('sharedFiles.previewError') }}
                            </p>
                            <div v-show="!loadingOffice && !officeError" ref="docxContainer" class="mx-auto bg-white" />
                        </div>
                    </div>

                    <!-- Spreadsheet preview — rendu table via SheetJS (lazy) -->
                    <div
                        v-else-if="isSpreadsheet"
                        class="flex max-h-[85vh] w-[88vw] max-w-5xl flex-col overflow-hidden rounded-xl bg-white"
                    >
                        <div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
                            <p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
                            <a
                                :href="downloadUrl"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                            >
                                {{ $t('sharedFiles.download') }}
                            </a>
                        </div>
                        <div v-if="sheetNames.length > 1" class="flex gap-1 overflow-x-auto border-b border-neutral-100 px-3 py-2">
                            <button
                                v-for="(name, i) in sheetNames"
                                :key="name"
                                class="whitespace-nowrap rounded px-2 py-1 text-xs"
                                :class="i === activeSheet ? 'bg-blue-600 text-white' : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'"
                                @click="selectSheet(i)"
                            >
                                {{ name }}
                            </button>
                        </div>
                        <div class="overflow-auto p-4">
                            <div v-if="loadingOffice" class="flex justify-center py-10">
                                <Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
                            </div>
                            <p v-else-if="officeError" class="py-10 text-center text-sm text-red-600">
                                {{ $t('sharedFiles.previewError') }}
                            </p>
                            <!-- eslint-disable-next-line vue/no-v-html -- HTML généré par SheetJS, valeurs de cellule échappées -->
                            <div v-else class="xlsx-host" v-html="sheetHtml" />
                        </div>
                    </div>

                    <!-- Generic file — download fallback -->
                    <div v-else class="flex flex-col items-center gap-4 rounded-xl bg-white p-10">
                        <Icon name="heroicons:document" class="h-16 w-16 text-neutral-400" />
                        <p class="max-w-xs truncate text-lg font-medium text-neutral-700">{{ entry.name }}</p>
                        <p class="text-sm text-neutral-400">{{ formatFileSize(entry.size) }}</p>
                        <a
                            :href="downloadUrl"
                            class="mt-2 rounded-lg bg-blue-600 px-6 py-2 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
                        >
                            {{ $t('sharedFiles.download') }}
                        </a>
                    </div>

                    <!-- File name footer (masqué pour les vues qui affichent déjà le nom dans leur en-tête) -->
                    <p v-if="!isText && !isDocx && !isSpreadsheet" class="mt-3 text-sm text-white/70">{{ entry.name }}</p>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<script setup lang="ts">
import type { FileEntry } from '~/modules/integration/services/dto/share'
import { useShareService } from '~/modules/integration/services/share'
import { formatFileSize } from '~/utils/format'

const props = defineProps<{
    entry: FileEntry | null
    hasPrev: boolean
    hasNext: boolean
}>()

defineEmits<{
    close: []
    prev: []
    next: []
}>()

const overlayRef = ref<HTMLElement | null>(null)
const textContent = ref('')
const loadingText = ref(false)

// Office previews (rendus côté client, libs chargées à la demande)
const docxContainer = ref<HTMLElement | null>(null)
const loadingOffice = ref(false)
const officeError = ref(false)
const sheetNames = ref<string[]>([])
const activeSheet = ref(0)
const sheetHtml = ref('')
// Workbook SheetJS courant (type laissé libre : la lib est importée dynamiquement)
let workbook: { SheetNames: string[]; Sheets: Record<string, unknown> } | null = null

const { getDownloadUrl } = useShareService()

const TEXT_RE = /\.(md|markdown|txt|csv|json|xml|log)$/i
const DOCX_RE = /\.docx$/i
const SHEET_RE = /\.(xlsx|xlsm|xls)$/i

const inlineUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'inline') : '')
const downloadUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'attachment') : '')
const isImage = computed(() => props.entry?.mimeType.startsWith('image/') ?? false)
const isPdf = computed(() => props.entry?.mimeType === 'application/pdf')
const isText = computed(() =>
    props.entry
        ? (props.entry.mimeType.startsWith('text/') || TEXT_RE.test(props.entry.name))
        : false
)
const isDocx = computed(() => props.entry ? DOCX_RE.test(props.entry.name) : false)
const isSpreadsheet = computed(() => props.entry ? SHEET_RE.test(props.entry.name) : false)

async function fetchBlob(): Promise<Blob> {
    return $fetch<Blob>(downloadUrl.value, {
        credentials: 'include',
        responseType: 'blob' as never,
    })
}

async function renderDocx(blob: Blob) {
    const [{ renderAsync }, DOMPurify] = await Promise.all([
        import('docx-preview'),
        import('dompurify'),
    ])
    loadingOffice.value = false
    await nextTick()
    if (docxContainer.value) {
        docxContainer.value.innerHTML = ''
        await renderAsync(blob, docxContainer.value, undefined, { inWrapper: true, ignoreLastRenderedPageBreak: true })
        // Anti-XSS : neutralise tout script injecté via un .docx piégé, en gardant la mise en forme (style)
        docxContainer.value.innerHTML = DOMPurify.default.sanitize(docxContainer.value.innerHTML, {
            ADD_TAGS: ['style'],
            FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'],
        })
    }
}

async function renderSpreadsheet(blob: Blob) {
    const [XLSX, DOMPurify] = await Promise.all([import('xlsx'), import('dompurify')])
    const buf = await blob.arrayBuffer()
    workbook = XLSX.read(buf, { type: 'array' }) as typeof workbook
    sheetNames.value = workbook?.SheetNames ?? []
    await selectSheet(0, XLSX, DOMPurify)
    loadingOffice.value = false
}

async function selectSheet(
    index: number,
    xlsx?: typeof import('xlsx'),
    purify?: typeof import('dompurify'),
) {
    if (!workbook) return
    activeSheet.value = index
    const XLSX = xlsx ?? (await import('xlsx'))
    const DOMPurify = purify ?? (await import('dompurify'))
    const ws = workbook.Sheets[workbook.SheetNames[index]!]
    const rawHtml = XLSX.utils.sheet_to_html(ws as never, { editable: false })
    sheetHtml.value = DOMPurify.default.sanitize(rawHtml, { FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'] })
}

function resetOffice() {
    loadingOffice.value = false
    officeError.value = false
    sheetHtml.value = ''
    sheetNames.value = []
    activeSheet.value = 0
    workbook = null
}

watch(() => props.entry, async (entry) => {
    textContent.value = ''
    resetOffice()
    if (!entry) return

    nextTick(() => overlayRef.value?.focus())

    if (isText.value) {
        loadingText.value = true
        try {
            textContent.value = await $fetch<string>(inlineUrl.value, {
                credentials: 'include',
                responseType: 'text' as never,
            })
        } catch {
            textContent.value = ''
        } finally {
            loadingText.value = false
        }
        return
    }

    if (isDocx.value || isSpreadsheet.value) {
        loadingOffice.value = true
        try {
            const blob = await fetchBlob()
            if (isDocx.value) {
                await renderDocx(blob)
            } else {
                await renderSpreadsheet(blob)
            }
        } catch {
            officeError.value = true
            loadingOffice.value = false
        }
    }
}, { immediate: true })
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

/* Rendu des tableurs (HTML généré par SheetJS) */
.xlsx-host :deep(table) {
    border-collapse: collapse;
    font-size: 12px;
}
.xlsx-host :deep(td),
.xlsx-host :deep(th) {
    border: 1px solid #e5e5e5;
    padding: 2px 6px;
    white-space: nowrap;
    text-align: left;
}
</style>
