<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Arquivo: src/features/documents/components/DocumentPreviewDialog.vue
| Preview inline de PDF/imagem + metadados + acoes.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, watch, computed } from 'vue'
import { useToast } from 'primevue/usetoast'

const props = defineProps({
    visible: { type: Boolean, default: false },
    doc: { type: Object, default: null },
    previewUrl: { type: String, default: '' }
})

const emit = defineEmits(['update:visible', 'download', 'edit', 'delete', 'share', 'sign'])

const toast = useToast()
const activeTab = ref('preview')

// ── Computed ────────────────────────────────────────────────

const isImage = computed(() => String(props.doc?.mime_type || '').startsWith('image/'))
const isPdf = computed(() => props.doc?.mime_type === 'application/pdf')
const canPreview = computed(() => isImage.value || isPdf.value)

const tipoLabel = computed(() => {
    const map = {
        laudo: 'Laudo', receita: 'Receita', exame: 'Exame',
        termo_assinado: 'Termo assinado', relatorio_externo: 'Relatório externo',
        identidade: 'Identidade', convenio: 'Convênio',
        declaracao: 'Declaração', atestado: 'Atestado',
        recibo: 'Recibo', outro: 'Outro'
    }
    return map[props.doc?.tipo_documento] || 'Documento'
})

const formattedSize = computed(() => {
    const b = props.doc?.tamanho_bytes
    if (!b) return '—'
    if (b < 1024) return b + ' B'
    if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB'
    return (b / (1024 * 1024)).toFixed(1) + ' MB'
})

const formattedDate = computed(() => {
    const d = props.doc?.uploaded_at
    if (!d) return '—'
    return new Date(d).toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })
})

const visibilidadeLabel = computed(() => {
    const map = {
        privado: 'Privado',
        compartilhado_supervisor: 'Supervisor',
        compartilhado_portal: 'Portal paciente'
    }
    return map[props.doc?.visibilidade] || 'Privado'
})

function close() {
    emit('update:visible', false)
}
</script>

<template>
    <Dialog
        :visible="visible"
        @update:visible="$emit('update:visible', $event)"
        modal
        maximizable
        :draggable="false"
        class="w-[55rem]"
        :breakpoints="{ '1199px': '90vw', '768px': '96vw' }"
        :pt="{
            header:  { class: '!p-4 !rounded-t-xl border-b border-[var(--surface-border)]' },
            content: { class: '!p-0' },
            footer:  { class: '!p-3 !rounded-b-xl border-t border-[var(--surface-border)]' }
        }"
        pt:mask:class="backdrop-blur-xs"
    >
        <template #header>
            <div class="flex items-center gap-3 flex-1 min-w-0">
                <span class="flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-500/10">
                    <i class="pi pi-eye text-indigo-500" />
                </span>
                <div class="min-w-0">
                    <div class="text-base font-semibold truncate">{{ doc?.nome_original }}</div>
                    <div class="text-xs text-[var(--text-color-secondary)]">{{ tipoLabel }} · {{ formattedSize }} · {{ formattedDate }}</div>
                </div>
            </div>
        </template>

        <div v-if="doc" class="flex flex-col lg:flex-row">
            <!-- Preview area -->
            <div class="flex-1 min-h-[400px] flex items-center justify-center bg-[var(--surface-ground)] p-4">
                <template v-if="canPreview && previewUrl">
                    <img
                        v-if="isImage"
                        :src="previewUrl"
                        :alt="doc.nome_original"
                        class="max-w-full max-h-[70vh] rounded shadow-sm"
                    />
                    <iframe
                        v-else-if="isPdf"
                        :src="previewUrl"
                        class="w-full h-[70vh] rounded border-0"
                    />
                </template>
                <div v-else class="flex flex-col items-center gap-3 text-[var(--text-color-secondary)]">
                    <i class="pi pi-file text-5xl opacity-40" />
                    <span class="text-sm">Preview não disponível para este tipo de arquivo.</span>
                    <Button label="Baixar arquivo" icon="pi pi-download" size="small" @click="emit('download', doc)" />
                </div>
            </div>

            <!-- Sidebar de detalhes -->
            <div class="w-full lg:w-[240px] border-t lg:border-t-0 lg:border-l border-[var(--surface-border)] p-4 flex flex-col gap-4">
                <div class="text-xs font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-1">Detalhes</div>

                <div class="flex flex-col gap-3">
                    <div>
                        <div class="text-[0.65rem] uppercase tracking-wider text-[var(--text-color-secondary)] mb-0.5">Tipo</div>
                        <div class="text-sm">{{ tipoLabel }}</div>
                    </div>
                    <div v-if="doc.categoria">
                        <div class="text-[0.65rem] uppercase tracking-wider text-[var(--text-color-secondary)] mb-0.5">Categoria</div>
                        <div class="text-sm">{{ doc.categoria }}</div>
                    </div>
                    <div>
                        <div class="text-[0.65rem] uppercase tracking-wider text-[var(--text-color-secondary)] mb-0.5">Visibilidade</div>
                        <div class="text-sm">{{ visibilidadeLabel }}</div>
                    </div>
                    <div v-if="doc.descricao">
                        <div class="text-[0.65rem] uppercase tracking-wider text-[var(--text-color-secondary)] mb-0.5">Descrição</div>
                        <div class="text-sm">{{ doc.descricao }}</div>
                    </div>
                    <div v-if="doc.tags?.length">
                        <div class="text-[0.65rem] uppercase tracking-wider text-[var(--text-color-secondary)] mb-1">Tags</div>
                        <div class="flex flex-wrap gap-1">
                            <span
                                v-for="tag in doc.tags"
                                :key="tag"
                                class="text-[0.65rem] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary"
                            >
                                {{ tag }}
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Acoes -->
                <div class="mt-auto flex flex-col gap-1.5 pt-3 border-t border-[var(--surface-border)]">
                    <Button label="Baixar" icon="pi pi-download" size="small" class="w-full" @click="emit('download', doc)" />
                    <Button label="Editar" icon="pi pi-pencil" size="small" text class="w-full" @click="emit('edit', doc)" />
                    <Button label="Compartilhar" icon="pi pi-share-alt" size="small" text class="w-full" @click="emit('share', doc)" />
                    <Button label="Assinar" icon="pi pi-check-square" size="small" text class="w-full" @click="emit('sign', doc)" />
                    <Button label="Excluir" icon="pi pi-trash" size="small" text severity="danger" class="w-full" @click="emit('delete', doc)" />
                </div>
            </div>
        </div>

        <template #footer>
            <div class="flex justify-end">
                <Button label="Fechar" text @click="close" />
            </div>
        </template>
    </Dialog>
</template>
