<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Arquivo: src/features/documents/components/DocumentGenerateDialog.vue
| Gerar documento: selecionar template, preencher, preview, gerar PDF.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, watch, computed } from 'vue'
import { useToast } from 'primevue/usetoast'
import { useDocumentGenerate } from '../composables/useDocumentGenerate'
import { useDocumentTemplates } from '../composables/useDocumentTemplates'
import { loadGeneratedFromDocId } from '@/services/DocumentGenerate.service'

const props = defineProps({
    visible: { type: Boolean, default: false },
    patientId: { type: String, default: null },
    patientName: { type: String, default: '' },
    agendaEventoId: { type: String, default: null },
    // Modo edicao: ID de um documents.id existente. Quando setado, o dialog
    // busca o template_id + dados_preenchidos do document_generated vinculado,
    // pre-seleciona o template e popula as variaveis. Save vira UPDATE
    // in-place (preserva documents.id e audit). Doc sem registro generated
    // (uploaded direto) cai no flow normal de "select template".
    editingDocId: { type: String, default: null }
})

const emit = defineEmits(['update:visible', 'generated'])

const toast = useToast()
const step = ref('select') // select | edit | preview

const {
    loading: generating,
    error: genError,
    variables,
    selectedTemplate,
    previewHtml,
    loadVariables,
    selectTemplate,
    setVariable,
    updatePreview,
    generateAndSave,
    downloadOnly,
    printDocument,
    reset
} = useDocumentGenerate()

const {
    templates,
    loading: loadingTemplates,
    fetchTemplates,
    TEMPLATE_VARIABLES
} = useDocumentTemplates()

// ── Reset ao abrir ──────────────────────────────────────────

watch(() => props.visible, async (v) => {
    if (!v) return;
    step.value = 'select'
    reset()
    await Promise.all([
        fetchTemplates(),
        props.patientId ? loadVariables(props.patientId, props.agendaEventoId) : Promise.resolve()
    ])

    // Modo edicao: tenta carregar o registro do generated, pre-seleciona
    // template e popula vars com dados_preenchidos (sobrescreve auto-vars
    // — preserva customizacao anterior do user). Se nao houver linkage
    // (doc uploaded direto), continua no flow normal de "select template".
    if (props.editingDocId) {
        const gen = await loadGeneratedFromDocId(props.editingDocId)
        if (gen?.template_id) {
            try {
                await selectTemplate(gen.template_id)
                // Merge: dados_preenchidos override auto-loaded variables.
                // Mantemos as vars que o user nao tinha customizado da vez
                // anterior (pra caso o template tenha vars novas adicionadas
                // depois) — pegamos as keys auto + sobrescreve com generated.
                const saved = gen.dados_preenchidos || {}
                Object.entries(saved).forEach(([k, val]) => {
                    setVariable(k, val == null ? '' : String(val))
                })
                step.value = 'edit'
            } catch (e) {
                toast.add({
                    severity: 'warn',
                    summary: 'Template original não encontrado',
                    detail: 'Selecione um template para regenerar o documento.',
                    life: 3500
                })
            }
        } else {
            toast.add({
                severity: 'info',
                summary: 'Documento legado',
                detail: 'Sem dados de edição. Selecione um template para regenerar.',
                life: 3500
            })
        }
    }
})

// ── Selecionar template ─────────────────────────────────────

async function onSelectTemplate(tpl) {
    await selectTemplate(tpl.id)
    step.value = 'edit'
}

// ── Variaveis editaveis ─────────────────────────────────────

const editableVars = computed(() => {
    if (!selectedTemplate.value?.variaveis?.length) return []
    return selectedTemplate.value.variaveis.map(key => {
        const meta = TEMPLATE_VARIABLES.find(v => v.key === key)
        return {
            key,
            label: meta?.label || key,
            grupo: meta?.grupo || 'Outros',
            source: meta?.source || '',
            value: variables.value[key] || ''
        }
    })
})

// Estatística pro topo: quantos campos vieram do auto-fill vs vazios
const varStats = computed(() => {
    const total = editableVars.value.length
    const filled = editableVars.value.filter(v => String(variables.value[v.key] || '').trim() !== '').length
    return { total, filled, empty: total - filled }
})

const varGroups = computed(() => {
    const groups = {}
    for (const v of editableVars.value) {
        if (!groups[v.grupo]) groups[v.grupo] = []
        groups[v.grupo].push(v)
    }
    return groups
})

function onVarChange(key, val) {
    setVariable(key, val)
}

// ── Gerar ───────────────────────────────────────────────────

async function onGenerate() {
    try {
        const result = await generateAndSave(props.patientId, props.editingDocId || null)
        toast.add({
            severity: 'success',
            summary: props.editingDocId ? 'Documento atualizado' : 'Documento salvo',
            detail: props.editingDocId
                ? 'PDF substituído com os novos valores.'
                : 'Disponível nos documentos do paciente.',
            life: 3000
        })
        emit('generated', result)
        close()
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao gerar PDF.' })
    }
}

async function onDownloadOnly() {
    try {
        await downloadOnly()
        toast.add({ severity: 'info', summary: 'Download', detail: 'PDF baixado (não salvo no sistema).', life: 3000 })
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e?.message || 'Falha ao gerar PDF.' })
    }
}

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

<template>
    <Dialog
        :visible="visible"
        @update:visible="$emit('update:visible', $event)"
        modal
        maximizable
        :draggable="false"
        :closable="!generating"
        :dismissableMask="!generating"
        class="w-[60rem]"
        :breakpoints="{ '1199px': '90vw', '768px': '96vw' }"
        :pt="{
            header:  { class: '!p-4 !rounded-t-xl border-b border-[var(--surface-border)]' },
            content: { class: '!p-4' },
            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">
                <span class="flex items-center justify-center w-8 h-8 rounded-lg bg-green-500/10">
                    <i :class="editingDocId ? 'pi pi-pencil text-amber-600' : 'pi pi-file-pdf text-green-600'" />
                </span>
                <div>
                    <div class="text-base font-semibold">{{ editingDocId ? 'Editar documento' : 'Gerar documento' }}</div>
                    <div class="text-xs text-[var(--text-color-secondary)]">
                        <template v-if="step === 'select'">Selecione um template</template>
                        <template v-else-if="step === 'edit'">{{ selectedTemplate?.nome_template }} — {{ patientName }}</template>
                        <template v-else>Preview do documento</template>
                    </div>
                </div>
            </div>
        </template>

        <!-- Step 1: Selecionar template -->
        <div v-if="step === 'select'">
            <div v-if="loadingTemplates" class="flex items-center justify-center py-12">
                <i class="pi pi-spinner pi-spin text-2xl text-[var(--text-color-secondary)]" />
            </div>
            <div v-else-if="!templates.length" class="text-center py-12 text-[var(--text-color-secondary)]">
                <i class="pi pi-inbox text-3xl opacity-40 mb-2" />
                <div class="text-sm">Nenhum template disponível.</div>
            </div>
            <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <button
                    v-for="tpl in templates"
                    :key="tpl.id"
                    class="flex items-start gap-3 p-3 rounded-lg border border-[var(--surface-border)] hover:border-primary hover:bg-primary/5 text-left transition-all"
                    @click="onSelectTemplate(tpl)"
                >
                    <span class="flex-shrink-0 w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center">
                        <i class="pi pi-file text-primary" />
                    </span>
                    <div class="min-w-0">
                        <div class="text-sm font-medium">{{ tpl.nome_template }}</div>
                        <div class="text-xs text-[var(--text-color-secondary)] mt-0.5">{{ tpl.descricao || tpl.tipo }}</div>
                        <span
                            v-if="tpl.is_global"
                            class="inline-block mt-1 text-[0.6rem] px-1.5 py-0.5 rounded-full bg-blue-500/10 text-blue-600"
                        >
                            padrão
                        </span>
                    </div>
                </button>
            </div>
        </div>

        <!-- Step 2: Editar variaveis -->
        <div v-else-if="step === 'edit'" class="flex flex-col gap-5">
            <!-- Resumo do preenchimento automático -->
            <div
                v-if="varStats.total"
                class="flex items-center gap-2 text-xs px-3 py-2 rounded-lg"
                :class="varStats.empty === 0
                    ? 'bg-green-500/10 text-green-700 dark:text-green-400'
                    : 'bg-amber-500/10 text-amber-700 dark:text-amber-400'"
            >
                <i :class="varStats.empty === 0 ? 'pi pi-check-circle' : 'pi pi-info-circle'" />
                <span v-if="varStats.empty === 0">
                    Todos os {{ varStats.total }} campos foram preenchidos automaticamente.
                </span>
                <span v-else>
                    {{ varStats.filled }} de {{ varStats.total }} preenchidos. Os campos vazios mostram onde cadastrar o dado.
                </span>
            </div>

            <!-- Erro de carregamento de variáveis -->
            <div
                v-if="genError"
                class="flex items-center gap-2 text-xs px-3 py-2 rounded-lg bg-red-500/10 text-red-600"
            >
                <i class="pi pi-exclamation-circle" />
                <span>{{ genError }}</span>
            </div>

            <div v-for="(vars, grupo) in varGroups" :key="grupo">
                <div class="text-xs font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-3">{{ grupo }}</div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div v-for="v in vars" :key="v.key" class="flex flex-col gap-1">
                        <FloatLabel variant="on">
                            <InputText
                                :id="`docgen-var-${v.key}`"
                                :modelValue="variables[v.key] || ''"
                                @update:modelValue="onVarChange(v.key, $event)"
                                class="w-full"
                                :invalid="!String(variables[v.key] || '').trim()"
                            />
                            <label :for="`docgen-var-${v.key}`">{{ v.label }}</label>
                        </FloatLabel>
                        <small
                            v-if="!String(variables[v.key] || '').trim() && v.source"
                            class="text-[0.65rem] text-[var(--text-color-secondary)] flex items-center gap-1 ml-1"
                        >
                            <i class="pi pi-link text-[0.55rem]" />
                            {{ v.source }}
                        </small>
                    </div>
                </div>
            </div>

            <div class="flex justify-end gap-2 mt-2">
                <Button label="Voltar" text icon="pi pi-arrow-left" @click="step = 'select'; reset()" />
                <Button label="Preview" icon="pi pi-eye" @click="updatePreview(); step = 'preview'" />
            </div>
        </div>

        <!-- Step 3: Preview -->
        <div v-else-if="step === 'preview'">
            <div class="border border-[var(--surface-border)] rounded-lg bg-white overflow-hidden">
                <iframe
                    :srcdoc="previewHtml"
                    class="w-full min-h-[60vh] border-0"
                    sandbox=""
                />
            </div>
        </div>

        <!-- Erro -->
        <div v-if="genError" class="mt-3 text-sm text-red-500 flex items-center gap-1.5">
            <i class="pi pi-exclamation-circle text-xs" />
            {{ genError }}
        </div>

        <template #footer>
            <div class="flex items-center justify-between gap-2">
                <div>
                    <Button
                        v-if="step === 'preview'"
                        label="Editar"
                        text
                        icon="pi pi-arrow-left"
                        @click="step = 'edit'"
                        :disabled="generating"
                    />
                </div>
                <div class="flex gap-2">
                    <Button label="Cancelar" text @click="close" :disabled="generating" />
                    <Button
                        v-if="step === 'preview'"
                        label="Só baixar"
                        text
                        icon="pi pi-download"
                        @click="onDownloadOnly"
                        :loading="generating"
                    />
                    <Button
                        v-if="step === 'preview'"
                        :label="editingDocId ? 'Substituir documento' : 'Salvar documento'"
                        icon="pi pi-check"
                        @click="onGenerate"
                        :loading="generating"
                    />
                </div>
            </div>
        </template>
    </Dialog>
</template>
