<!--
|--------------------------------------------------------------------------
| 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'

const props = defineProps({
    visible: { type: Boolean, default: false },
    patientId: { type: String, default: null },
    patientName: { type: String, default: '' },
    agendaEventoId: { 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) {
        step.value = 'select'
        reset()
        await Promise.all([
            fetchTemplates(),
            props.patientId ? loadVariables(props.patientId, props.agendaEventoId) : Promise.resolve()
        ])
    }
})

// ── 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',
            value: variables.value[key] || ''
        }
    })
})

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)
        toast.add({ severity: 'success', summary: 'Documento salvo', detail: '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="pi pi-file-pdf text-green-600" />
                </span>
                <div>
                    <div class="text-base font-semibold">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-4">
            <div v-for="(vars, grupo) in varGroups" :key="grupo">
                <div class="text-xs font-semibold uppercase tracking-wider text-[var(--text-color-secondary)] mb-2">{{ grupo }}</div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div v-for="v in vars" :key="v.key" class="flex flex-col gap-1">
                        <label class="text-xs text-[var(--text-color-secondary)]">{{ v.label }}</label>
                        <InputText
                            :modelValue="variables[v.key] || ''"
                            @update:modelValue="onVarChange(v.key, $event)"
                            class="w-full"
                        />
                    </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="Salvar documento"
                        icon="pi pi-check"
                        @click="onGenerate"
                        :loading="generating"
                    />
                </div>
            </div>
        </template>
    </Dialog>
</template>
