<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/features/documents/DocumentTemplatesPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useToast } from 'primevue/usetoast'
import { useConfirm } from 'primevue/useconfirm'
import Menu from 'primevue/menu'

import { useDocumentTemplates } from './composables/useDocumentTemplates'
import DocumentTemplateEditor from './components/DocumentTemplateEditor.vue'

const toast = useToast()
const confirm = useConfirm()

const {
    templates, loading, error,
    globalTemplates, tenantTemplates,
    TIPOS_TEMPLATE,
    fetchTemplates, create, update, remove, duplicate
} = useDocumentTemplates()

// ── Views ───────────────────────────────────────────────────

const view = ref('list')  // list | create | edit
const editingTemplate = ref({})
const editingId = ref(null)

// ── Hero sticky ─────────────────────────────────────────────

const headerEl = ref(null)
const headerSentinelRef = ref(null)
const headerStuck = ref(false)
let _observer = null

// ── Mobile menu ─────────────────────────────────────────────

const mobileMenuRef = ref(null)
const mobileMenuItems = [
    { label: 'Novo template', icon: 'pi pi-plus', command: () => openCreate() },
    { separator: true },
    { label: 'Atualizar', icon: 'pi pi-refresh', command: () => fetchTemplates(true) }
]

// ── Lifecycle ───────────────────────────────────────────────

onMounted(() => {
    const rootMargin = `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px`
    _observer = new IntersectionObserver(
        ([entry]) => { headerStuck.value = !entry.isIntersecting },
        { threshold: 0, rootMargin }
    )
    if (headerSentinelRef.value) _observer.observe(headerSentinelRef.value)
    fetchTemplates(true)
})

onBeforeUnmount(() => {
    _observer?.disconnect()
})

// ── Acoes ───────────────────────────────────────────────────

function openCreate() {
    editingId.value = null
    editingTemplate.value = {}
    view.value = 'create'
}

function openEdit(tpl) {
    if (tpl.is_global) {
        toast.add({ severity: 'warn', summary: 'Somente leitura', detail: 'Templates padrão não podem ser editados. Duplique para personalizar.', life: 3000 })
        return
    }
    editingId.value = tpl.id
    editingTemplate.value = { ...tpl }
    view.value = 'edit'
}

async function onSave(payload) {
    try {
        if (view.value === 'create') {
            await create(payload)
            toast.add({ severity: 'success', summary: 'Criado', detail: payload.nome_template, life: 3000 })
        } else {
            await update(editingId.value, payload)
            toast.add({ severity: 'success', summary: 'Salvo', detail: payload.nome_template, life: 3000 })
        }
        view.value = 'list'
        fetchTemplates(true)
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
    }
}

function onDuplicate(tpl) {
    confirm.require({
        message: `Deseja copiar "${tpl.nome_template}" para os seus templates? Você poderá editá-lo livremente.`,
        header: 'Duplicar template',
        icon: 'pi pi-copy',
        acceptLabel: 'Copiar',
        rejectLabel: 'Cancelar',
        accept: async () => {
            try {
                await duplicate(tpl.id)
                toast.add({ severity: 'success', summary: 'Duplicado', detail: `"${tpl.nome_template}" copiado para Meus Templates.`, life: 3000 })
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
            }
        }
    })
}

function onDelete(tpl) {
    confirm.require({
        message: `Desativar template "${tpl.nome_template}"?`,
        header: 'Confirmar',
        icon: 'pi pi-exclamation-triangle',
        accept: async () => {
            try {
                await remove(tpl.id)
                toast.add({ severity: 'success', summary: 'Desativado', life: 2000 })
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e?.message })
            }
        }
    })
}

function onCancel() {
    view.value = 'list'
}

// ── Tipo label ──────────────────────────────────────────────

function tipoLabel(tipo) {
    return TIPOS_TEMPLATE.find(t => t.value === tipo)?.label || tipo
}

// ── Template card menu ──────────────────────────────────────

function getCardMenuItems(tpl) {
    const items = [
        { label: 'Duplicar', icon: 'pi pi-copy', command: () => onDuplicate(tpl) }
    ]
    if (!tpl.is_global) {
        items.push(
            { label: 'Editar', icon: 'pi pi-pencil', command: () => openEdit(tpl) },
            { separator: true },
            { label: 'Desativar', icon: 'pi pi-trash', class: 'text-red-500', command: () => onDelete(tpl) }
        )
    }
    return items
}
</script>

<template>
    <!-- Sentinel -->
    <div ref="headerSentinelRef" class="h-px" />

    <!-- Hero sticky -->
    <div
        ref="headerEl"
        class="sticky my-3 md:mx-4 z-20 overflow-hidden rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] px-3 py-2.5 transition-[border-radius] duration-200"
        :class="{ 'rounded-tl-none rounded-tr-none': headerStuck }"
        :style="{ top: 'var(--layout-sticky-top, 56px)' }"
    >
        <!-- Blobs decorativos -->
        <div class="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden="true">
            <div class="absolute w-64 h-64 -top-16 -right-8 rounded-full blur-[60px] bg-indigo-500/10" />
            <div class="absolute w-72 h-72 top-0 -left-16 rounded-full blur-[60px] bg-emerald-400/9" />
        </div>

        <div class="relative z-1 flex items-center gap-3">
            <!-- Voltar (create/edit) + Brand -->
            <div class="flex items-center gap-2 shrink-0">
                <Button v-if="view !== 'list'" icon="pi pi-arrow-left" text severity="secondary" class="h-9 w-9 rounded-full shrink-0" v-tooltip.bottom="'Voltar à lista'" @click="view = 'list'" />
                <div class="grid place-items-center w-9 h-9 rounded-md shrink-0 bg-indigo-500/10 text-indigo-500">
                    <i class="pi pi-file-edit text-base" />
                </div>
                <div class="min-w-0 hidden lg:block">
                    <div class="text-[1rem] font-bold tracking-tight text-[var(--text-color)]">
                        <template v-if="view === 'list'">Templates de documentos</template>
                        <template v-else-if="view === 'create'">Novo template</template>
                        <template v-else>Editar template</template>
                    </div>
                    <div class="text-[0.75rem] text-[var(--text-color-secondary)]">Modelos para declarações, atestados, recibos e outros documentos</div>
                </div>
            </div>

            <!-- Ações LIST (desktop) -->
            <div v-if="view === 'list'" class="hidden xl:flex items-center gap-1 shrink-0 ml-auto">
                <Button icon="pi pi-refresh" severity="secondary" outlined class="h-9 w-9 rounded-full" :loading="loading" v-tooltip.bottom="'Atualizar'" @click="fetchTemplates(true)" />
                <Button label="Novo template" icon="pi pi-plus" size="small" class="rounded-full" @click="openCreate" />
            </div>

            <!-- Ações LIST (mobile) -->
            <div v-if="view === 'list'" class="flex xl:hidden items-center gap-1 shrink-0 ml-auto">
                <Button icon="pi pi-plus" class="h-9 w-9 rounded-full" @click="openCreate" />
                <Button label="Ações" icon="pi pi-ellipsis-v" severity="secondary" size="small" class="rounded-full" @click="(e) => mobileMenuRef.toggle(e)" />
                <Menu ref="mobileMenuRef" :model="mobileMenuItems" :popup="true" />
            </div>

            <!-- Ações CREATE/EDIT (desktop) -->
            <div v-if="view !== 'list'" class="hidden sm:flex items-center gap-1 shrink-0 ml-auto">
                <Button label="Cancelar" severity="secondary" outlined size="small" class="rounded-full" @click="view = 'list'" />
                <Button :label="view === 'create' ? 'Criar template' : 'Salvar'" icon="pi pi-check" size="small" class="rounded-full" @click="onSave(editingTemplate)" />
            </div>

            <!-- Ações CREATE/EDIT (mobile — só ícones) -->
            <div v-if="view !== 'list'" class="flex sm:hidden items-center gap-1 shrink-0 ml-auto">
                <Button icon="pi pi-times" severity="secondary" outlined class="h-9 w-9 rounded-full" v-tooltip.bottom="'Cancelar'" @click="view = 'list'" />
                <Button icon="pi pi-check" class="h-9 w-9 rounded-full" v-tooltip.bottom="view === 'create' ? 'Criar template' : 'Salvar'" @click="onSave(editingTemplate)" />
            </div>
        </div>
    </div>

    <!-- Conteúdo -->
    <div class="px-3 md:px-4 pb-8 flex flex-col gap-3 xl:gap-4">
        <!-- ══ LIST VIEW ══════════════════════════════════════════ -->
        <template v-if="view === 'list'">
            <!-- Loading -->
            <div v-if="loading" class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] flex items-center justify-center py-16">
                <i class="pi pi-spinner pi-spin text-2xl text-[var(--text-color-secondary)]" />
            </div>

            <!-- Empty (nenhum template) -->
            <div v-else-if="!templates.length" class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] overflow-hidden">
                <div class="flex items-center justify-between px-4 py-3 border-b border-[var(--surface-border,#e2e8f0)]">
                    <div class="flex items-center gap-2 min-w-0">
                        <i class="pi pi-file-edit text-[var(--text-color-secondary)] opacity-60" />
                        <span class="font-semibold text-sm">Templates cadastrados</span>
                    </div>
                    <span class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-[var(--surface-200,#e5e7eb)] text-[var(--text-color-secondary)] text-[0.72rem] font-bold">0</span>
                </div>
                <div class="py-10 px-6 text-center">
                    <i class="pi pi-file-edit text-2xl opacity-20 mb-2 block" />
                    <div class="font-semibold text-sm">Nenhum template encontrado</div>
                    <div class="text-xs opacity-60 mt-1">Crie seu primeiro template personalizado</div>
                    <Button label="Criar primeiro template" icon="pi pi-plus" severity="secondary" outlined size="small" class="rounded-full mt-3" @click="openCreate" />
                </div>
            </div>

            <template v-else>
                <!-- Templates globais (padrão) -->
                <div v-if="globalTemplates.length" class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] overflow-hidden">
                    <div class="flex items-center justify-between px-4 py-3 border-b border-[var(--surface-border,#e2e8f0)]">
                        <div class="flex items-center gap-2 min-w-0">
                            <i class="pi pi-shield text-[var(--text-color-secondary)] opacity-60" />
                            <span class="font-semibold text-sm">Templates padrão do sistema</span>
                        </div>
                        <span class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-blue-500/10 text-blue-600 text-[0.72rem] font-bold">{{ globalTemplates.length }}</span>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3 p-3">
                        <div
                            v-for="tpl in globalTemplates"
                            :key="tpl.id"
                            class="group relative flex flex-col p-4 rounded-md border border-[var(--surface-border,#e2e8f0)] hover:border-[var(--primary-color,#6366f1)] hover:bg-[var(--surface-hover,#f1f5f9)] transition-all duration-150 cursor-pointer"
                            @click="onDuplicate(tpl)"
                        >
                            <div class="flex items-start gap-3">
                                <span class="shrink-0 w-9 h-9 rounded-md bg-blue-500/10 grid place-items-center">
                                    <i class="pi pi-file text-blue-500" />
                                </span>
                                <div class="min-w-0 flex-1">
                                    <div class="text-sm font-semibold text-[var(--text-color)] line-clamp-1">{{ tpl.nome_template }}</div>
                                    <div class="text-xs text-[var(--text-color-secondary)] mt-0.5">{{ tipoLabel(tpl.tipo) }}</div>
                                    <div v-if="tpl.descricao" class="text-xs text-[var(--text-color-secondary)] mt-1 line-clamp-2 opacity-75">{{ tpl.descricao }}</div>
                                </div>
                            </div>
                            <span class="absolute top-2 right-2 text-[0.6rem] font-semibold px-1.5 py-0.5 rounded-full bg-blue-500/10 text-blue-600">padrão</span>
                            <div class="mt-2 text-[0.7rem] text-[var(--text-color-secondary)] opacity-0 group-hover:opacity-100 transition-opacity">
                                <i class="pi pi-copy text-[0.7rem] mr-1" />Clique para duplicar e personalizar
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Templates do tenant -->
                <div v-if="tenantTemplates.length" class="rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] overflow-hidden">
                    <div class="flex items-center justify-between px-4 py-3 border-b border-[var(--surface-border,#e2e8f0)]">
                        <div class="flex items-center gap-2 min-w-0">
                            <i class="pi pi-user-edit text-[var(--text-color-secondary)] opacity-60" />
                            <span class="font-semibold text-sm">Meus templates</span>
                        </div>
                        <span class="inline-flex items-center justify-center min-w-[22px] h-[22px] px-1.5 rounded-full bg-[var(--primary-color,#6366f1)] text-white text-[0.72rem] font-bold">{{ tenantTemplates.length }}</span>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3 p-3">
                        <div
                            v-for="tpl in tenantTemplates"
                            :key="tpl.id"
                            class="group relative flex flex-col p-4 rounded-md border border-[var(--surface-border,#e2e8f0)] hover:border-[var(--primary-color,#6366f1)] hover:bg-[var(--primary-color,#6366f1)]/5 transition-all duration-150 cursor-pointer"
                            @click="openEdit(tpl)"
                        >
                            <div class="flex items-start gap-3">
                                <span class="shrink-0 w-9 h-9 rounded-md bg-indigo-500/10 grid place-items-center">
                                    <i class="pi pi-file-edit text-indigo-500" />
                                </span>
                                <div class="min-w-0 flex-1">
                                    <div class="text-sm font-semibold text-[var(--text-color)] line-clamp-1">{{ tpl.nome_template }}</div>
                                    <div class="text-xs text-[var(--text-color-secondary)] mt-0.5">{{ tipoLabel(tpl.tipo) }}</div>
                                    <div v-if="tpl.descricao" class="text-xs text-[var(--text-color-secondary)] mt-1 line-clamp-2 opacity-75">{{ tpl.descricao }}</div>
                                </div>
                            </div>

                            <!-- Menu de ações -->
                            <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                <Button
                                    icon="pi pi-ellipsis-v"
                                    text
                                    rounded
                                    size="small"
                                    class="!w-7 !h-7"
                                    @click.stop="$refs[`menu_${tpl.id}`]?.[0]?.toggle($event)"
                                />
                                <Menu :ref="`menu_${tpl.id}`" :model="getCardMenuItems(tpl)" :popup="true" />
                            </div>

                            <div class="flex items-center gap-2 mt-2">
                                <span v-if="!tpl.ativo" class="text-[0.6rem] font-semibold px-1.5 py-0.5 rounded-full bg-red-500/10 text-red-500">inativo</span>
                                <span class="text-[0.65rem] text-[var(--text-color-secondary)]">
                                    <i class="pi pi-code text-[0.6rem] mr-0.5" />{{ tpl.variaveis?.length || 0 }} variáveis
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </template>

        <!-- ══ CREATE / EDIT VIEW ═════════════════════════════════ -->
        <template v-if="view === 'create' || view === 'edit'">
            <DocumentTemplateEditor
                v-model="editingTemplate"
                :mode="view"
                @save="onSave"
                @cancel="onCancel"
            />
        </template>
    </div>

    <ConfirmDialog />
</template>
