<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/views/pages/saas/SaasEmailTemplatesPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import Editor from 'primevue/editor';
import { supabase } from '@/lib/supabase/client';
import { renderEmail } from '@/lib/email/emailTemplateService';
import { MOCK_DATA, TEMPLATE_DOMAINS } from '@/lib/email/emailTemplateConstants';

const toast = useToast();

// ── Perfil (logo no preview) ───────────────────────────────────
const profileLogoUrl = ref(null);

async function loadProfile() {
    const {
        data: { user }
    } = await supabase.auth.getUser();
    if (!user) return;
    const { data } = await supabase.from('profiles').select('avatar_url').eq('id', user.id).maybeSingle();
    profileLogoUrl.value = data?.avatar_url || null;
}

// ── Lista ──────────────────────────────────────────────────────
const templates = ref([]);
const loading = ref(false);
const filterDomain = ref(null);

async function load() {
    loading.value = true;
    try {
        const { data, error } = await supabase.from('email_templates_global').select('*').order('domain').order('key');
        if (error) throw error;
        templates.value = data;
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao carregar', detail: e.message, life: 4000 });
    } finally {
        loading.value = false;
    }
}

const filtered = computed(() => {
    if (!filterDomain.value) return templates.value;
    return templates.value.filter((t) => t.domain === filterDomain.value);
});

const DOMAIN_OPTIONS = [
    { label: 'Todos', value: null },
    { label: 'Sessão', value: TEMPLATE_DOMAINS.SESSION },
    { label: 'Triagem', value: TEMPLATE_DOMAINS.INTAKE },
    { label: 'Sistema', value: TEMPLATE_DOMAINS.SYSTEM },
    { label: 'Financeiro', value: TEMPLATE_DOMAINS.BILLING }
];

const DOMAIN_SELECT_OPTIONS = [
    { label: 'Sessão', value: TEMPLATE_DOMAINS.SESSION },
    { label: 'Triagem', value: TEMPLATE_DOMAINS.INTAKE },
    { label: 'Sistema', value: TEMPLATE_DOMAINS.SYSTEM },
    { label: 'Financeiro', value: TEMPLATE_DOMAINS.BILLING }
];

const DOMAIN_LABEL = { session: 'Sessão', intake: 'Triagem', billing: 'Financeiro', system: 'Sistema' };
const DOMAIN_SEVERITY = { session: 'info', intake: 'warning', billing: 'success', system: 'secondary' };

// ── Variables editor helpers ───────────────────────────────────
// Trabalha internamente como array de {key, description} para o editor dinâmico

const varRows = ref([]); // [{ key: string, description: string }]

function _objectToRows(obj) {
    return Object.entries(obj || {}).map(([key, description]) => ({ key, description: String(description) }));
}

function _rowsToObject(rows) {
    const obj = {};
    rows.forEach((r) => {
        const k = r.key?.trim();
        if (k) obj[k] = r.description || '';
    });
    return obj;
}

function addVarRow() {
    varRows.value.push({ key: '', description: '' });
}

function removeVarRow(idx) {
    varRows.value.splice(idx, 1);
}

// ── Dialog edição / criação ────────────────────────────────────
const dlg = ref({ open: false, saving: false, id: null, isNew: false });
const form = ref({});
const editorRef = ref(null);

function openNew() {
    form.value = {
        key: '',
        domain: TEMPLATE_DOMAINS.SESSION,
        subject: '',
        body_html: '',
        body_text: '',
        is_active: true
    };
    varRows.value = [];
    dlg.value = { open: true, saving: false, id: null, isNew: true };
}

function openEdit(t) {
    form.value = {
        key: t.key,
        domain: t.domain,
        subject: t.subject,
        body_html: t.body_html,
        body_text: t.body_text ?? '',
        version: t.version,
        is_active: t.is_active
    };
    varRows.value = _objectToRows(t.variables);
    dlg.value = { open: true, saving: false, id: t.id, isNew: false };
}

function closeDlg() {
    dlg.value.open = false;
}

const dlgHeader = computed(() => (dlg.value.isNew ? 'Novo Template Global' : `Editar — ${form.value.key}`));

// Chaves disponíveis para inserção rápida no editor
const formVariables = computed(() => {
    const keys = varRows.value.map((r) => r.key).filter(Boolean);
    if (!keys.includes('clinic_logo_url')) keys.push('clinic_logo_url');
    return keys;
});

// Insere {{varName}} na posição do cursor no Editor (Quill)
function insertVar(varName) {
    const snippet = `{{${varName}}}`;
    const quill = editorRef.value?.quill;
    if (!quill) {
        form.value.body_html = (form.value.body_html || '') + snippet;
        return;
    }
    const range = quill.getSelection(true);
    const index = range ? range.index : quill.getLength() - 1;
    quill.insertText(index, snippet, 'user');
    quill.setSelection(index + snippet.length, 0);
}

async function save() {
    if (!form.value.subject?.trim()) {
        toast.add({ severity: 'warn', summary: 'Subject é obrigatório', life: 3000 });
        return;
    }
    if (!form.value.body_html?.trim()) {
        toast.add({ severity: 'warn', summary: 'Body HTML é obrigatório', life: 3000 });
        return;
    }
    if (dlg.value.isNew && !form.value.key?.trim()) {
        toast.add({ severity: 'warn', summary: 'Key é obrigatória', life: 3000 });
        return;
    }

    const variables = _rowsToObject(varRows.value);
    dlg.value.saving = true;

    try {
        if (dlg.value.isNew) {
            // INSERT — version começa em 1
            const { error } = await supabase.from('email_templates_global').insert({
                key: form.value.key.trim(),
                domain: form.value.domain,
                channel: 'email',
                subject: form.value.subject.trim(),
                body_html: form.value.body_html,
                body_text: form.value.body_text || null,
                version: 1,
                is_active: form.value.is_active,
                variables
            });
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Template criado', detail: 'v1', life: 3000 });
        } else {
            // UPDATE — incrementa version automaticamente
            const nextVersion = (form.value.version || 1) + 1;
            const { error } = await supabase
                .from('email_templates_global')
                .update({
                    subject: form.value.subject.trim(),
                    body_html: form.value.body_html,
                    body_text: form.value.body_text || null,
                    version: nextVersion,
                    is_active: form.value.is_active,
                    variables
                })
                .eq('id', dlg.value.id);
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Template salvo', detail: `Versão ${nextVersion}`, life: 3000 });
        }
        closeDlg();
        await load();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 5000 });
    } finally {
        dlg.value.saving = false;
    }
}

async function toggleActive(t) {
    try {
        const { error } = await supabase.from('email_templates_global').update({ is_active: !t.is_active }).eq('id', t.id);
        if (error) throw error;
        await load();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
    }
}

// ── Dialog preview ─────────────────────────────────────────────
const preview = ref({ open: false, subject: '', body_html: '', key: '' });

function openPreview(t) {
    const mock = {
        ..._mockForDomain(t.domain),
        clinic_logo_url: profileLogoUrl.value || null
    };
    const rendered = renderEmail(t, mock);
    preview.value = { open: true, ...rendered, key: t.key };
}

function _mockForDomain(domain) {
    if (domain === TEMPLATE_DOMAINS.SESSION) return { ...MOCK_DATA.session };
    if (domain === TEMPLATE_DOMAINS.INTAKE) return { ...MOCK_DATA.intake };
    return { ...MOCK_DATA.system };
}

onMounted(() => {
    load();
    loadProfile();
});
</script>

<template>
    <div class="flex flex-col gap-4 p-4">
        <!-- Header -->
        <div class="cfg-subheader">
            <div class="cfg-subheader__icon"><i class="pi pi-envelope" /></div>
            <div class="min-w-0 flex-1">
                <div class="cfg-subheader__title">Templates de E-mail Globais</div>
                <div class="cfg-subheader__sub">Templates base do sistema. Tenants podem criar overrides sem alterar estes.</div>
            </div>
            <div class="flex gap-2 shrink-0">
                <Button icon="pi pi-refresh" severity="secondary" text :loading="loading" v-tooltip.bottom="'Recarregar'" @click="load" />
                <Button label="Novo template" icon="pi pi-plus" size="small" @click="openNew" />
            </div>
        </div>

        <!-- Filtro por domain -->
        <div class="flex gap-2 mb-4 flex-wrap">
            <Button
                v-for="opt in DOMAIN_OPTIONS"
                :key="String(opt.value)"
                :label="opt.label"
                size="small"
                :severity="filterDomain === opt.value ? 'primary' : 'secondary'"
                :outlined="filterDomain !== opt.value"
                @click="filterDomain = opt.value"
            />
        </div>

        <!-- Loading -->
        <div v-if="loading" class="flex justify-center py-12">
            <ProgressSpinner />
        </div>

        <!-- Lista -->
        <div v-else class="flex flex-col gap-2">
            <div
                v-for="t in filtered"
                :key="t.id"
                class="border border-(--surface-border) rounded-xl bg-(--surface-card) px-4 py-3 flex gap-3 items-center"
                :class="{ 'opacity-50': !t.is_active }"
            >
                <Tag :value="DOMAIN_LABEL[t.domain] ?? t.domain" :severity="DOMAIN_SEVERITY[t.domain] ?? 'secondary'" class="text-[0.7rem] shrink-0" />
                <div class="flex-1 min-w-0">
                    <div class="font-mono text-xs text-(--text-color-secondary) mb-0.5">{{ t.key }}</div>
                    <div class="text-sm truncate font-medium">{{ t.subject }}</div>
                </div>
                <div class="hidden md:flex items-center gap-3 text-xs text-(--text-color-secondary) shrink-0">
                    <span>v{{ t.version }}</span>
                    <Tag :value="t.channel" severity="secondary" class="text-[0.65rem]" />
                </div>
                <div class="flex items-center gap-1 shrink-0">
                    <Button icon="pi pi-eye" text rounded size="small" severity="secondary" title="Preview" @click="openPreview(t)" />
                    <Button icon="pi pi-pencil" text rounded size="small" title="Editar" @click="openEdit(t)" />
                    <Button
                        :icon="t.is_active ? 'pi pi-eye-slash' : 'pi pi-check-circle'"
                        text
                        rounded
                        size="small"
                        :severity="t.is_active ? 'secondary' : 'success'"
                        :title="t.is_active ? 'Desativar' : 'Ativar'"
                        @click="toggleActive(t)"
                    />
                </div>
            </div>

            <div v-if="!filtered.length" class="text-center py-12 text-(--text-color-secondary)">
                <i class="pi pi-envelope text-4xl opacity-30 block mb-3" />
                Nenhum template neste domínio.
            </div>
        </div>

        <!-- ── Dialog Edição / Criação ──────────────────────────────── -->
        <Dialog v-model:visible="dlg.open" :header="dlgHeader" modal :style="{ width: '880px', maxWidth: '96vw' }" :draggable="false">
            <div class="flex flex-col gap-5 py-2">

                <!-- Key + Domain (linha só no modo criação; no edit: readonly labels) -->
                <div v-if="dlg.isNew" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="flex flex-col gap-1.5">
                        <label class="text-xs font-semibold">Key *<span class="font-normal opacity-60 ml-1">(ex: session.reminder.email)</span></label>
                        <InputText v-model="form.key" placeholder="domain.nome.email" class="w-full font-mono" />
                    </div>
                    <div class="flex flex-col gap-1.5">
                        <label class="text-xs font-semibold">Domain *</label>
                        <Select v-model="form.domain" :options="DOMAIN_SELECT_OPTIONS" option-label="label" option-value="value" class="w-full" />
                    </div>
                </div>

                <div v-else class="flex items-center gap-3 text-sm">
                    <Tag :value="DOMAIN_LABEL[form.domain] ?? form.domain" :severity="DOMAIN_SEVERITY[form.domain] ?? 'secondary'" />
                    <span class="font-mono text-(--text-color-secondary)">{{ form.key }}</span>
                    <span class="ml-auto text-xs text-(--text-color-secondary) opacity-70">v{{ form.version }} → v{{ (form.version || 1) + 1 }} ao salvar</span>
                </div>

                <!-- Subject -->
                <div class="flex flex-col gap-1.5">
                    <label class="text-xs font-semibold">Subject *</label>
                    <InputText v-model="form.subject" class="w-full" placeholder="Assunto do e-mail — suporta {{variavel}}" />
                </div>

                <!-- Body HTML -->
                <div class="flex flex-col gap-2">
                    <label class="text-xs font-semibold">Body HTML *</label>
                    <Editor ref="editorRef" v-model="form.body_html" editor-style="min-height: 240px; font-size: 0.85rem;" />

                    <!-- Botões de inserção de variáveis -->
                    <div v-if="formVariables.length" class="flex flex-col gap-1.5">
                        <span class="text-xs text-(--text-color-secondary)">Inserir variável no cursor:</span>
                        <div class="flex flex-wrap gap-1.5">
                            <Button
                                v-for="v in formVariables"
                                :key="v"
                                :label="`{{${v}}}`"
                                size="small"
                                severity="secondary"
                                outlined
                                class="font-mono text-[0.68rem]! py-1! px-2!"
                                @click="insertVar(v)"
                            />
                        </div>
                    </div>

                    <p class="text-xs text-(--text-color-secondary) m-0">
                        Suporta <code>&#123;&#123;variavel&#125;&#125;</code> e
                        <code>&#123;&#123;#if variavel&#125;&#125;...&#123;&#123;/if&#125;&#125;</code>
                    </p>
                </div>

                <!-- Body Text -->
                <div class="flex flex-col gap-1.5">
                    <label class="text-xs font-semibold">
                        Body Text
                        <span class="font-normal opacity-60">(opcional — gerado do HTML se vazio)</span>
                    </label>
                    <Textarea v-model="form.body_text" rows="2" class="w-full text-xs" auto-resize />
                </div>

                <!-- Variables editor -->
                <div class="flex flex-col gap-2">
                    <div class="flex items-center justify-between">
                        <label class="text-xs font-semibold">Variáveis disponíveis</label>
                        <Button label="Adicionar variável" icon="pi pi-plus" size="small" severity="secondary" text @click="addVarRow" />
                    </div>

                    <div v-if="varRows.length === 0" class="text-xs text-(--text-color-secondary) italic py-1">
                        Nenhuma variável definida. Clique em "Adicionar variável" para incluir.
                    </div>

                    <div v-else class="flex flex-col gap-2">
                        <div v-for="(row, idx) in varRows" :key="idx" class="flex gap-2 items-center">
                            <InputText
                                v-model="row.key"
                                placeholder="chave"
                                class="font-mono flex-[0_0_200px] text-sm"
                                size="small"
                            />
                            <InputText
                                v-model="row.description"
                                placeholder="Descrição da variável"
                                class="flex-1 text-sm"
                                size="small"
                            />
                            <Button icon="pi pi-times" text rounded size="small" severity="danger" @click="removeVarRow(idx)" />
                        </div>
                    </div>

                    <p class="text-xs text-(--text-color-secondary) m-0 mt-1">
                        Estas chaves ficam salvas no campo <code>variables</code> e guiam os tenants ao customizar o template.
                    </p>
                </div>

                <!-- Ativo toggle -->
                <div class="flex items-center gap-2 pt-1 border-t border-(--surface-border)">
                    <ToggleSwitch v-model="form.is_active" inputId="sw-active-global" />
                    <label for="sw-active-global" class="text-sm cursor-pointer select-none">Template ativo</label>
                </div>
            </div>

            <template #footer>
                <Button label="Cancelar" text @click="closeDlg" :disabled="dlg.saving" />
                <Button
                    :label="dlg.isNew ? 'Criar template' : 'Salvar'"
                    icon="pi pi-check"
                    :loading="dlg.saving"
                    @click="save"
                />
            </template>
        </Dialog>

        <!-- ── Dialog Preview ────────────────────────────────────── -->
        <Dialog v-model:visible="preview.open" :header="`Preview — ${preview.key}`" modal :style="{ width: '700px', maxWidth: '96vw' }" :draggable="false">
            <div class="flex flex-col gap-3">
                <div class="border border-(--surface-border) rounded-lg p-3 bg-(--surface-ground)">
                    <span class="text-xs font-semibold text-(--text-color-secondary) uppercase tracking-widest">Subject</span>
                    <p class="mt-1 mb-0 font-medium">{{ preview.subject }}</p>
                </div>

                <div class="border border-(--surface-border) rounded-lg p-5 bg-white text-gray-800">
                    <div v-if="profileLogoUrl" class="mb-4 text-center">
                        <img :src="profileLogoUrl" alt="Logo" class="h-10 object-contain inline-block" />
                    </div>
                    <!-- eslint-disable-next-line vue/no-v-html -->
                    <div class="text-sm leading-relaxed" v-html="preview.body_html" />
                </div>

                <p class="text-xs text-(--text-color-secondary) m-0 text-center">
                    Preview com dados de exemplo.
                    <span v-if="profileLogoUrl"> Logo do seu perfil.</span>
                    <span v-else> Sem logo — configure em <b>Meu Perfil → Avatar</b>.</span>
                </p>
            </div>

            <template #footer>
                <Button label="Fechar" @click="preview.open = false" />
            </template>
        </Dialog>
    </div>
</template>
