<!--
|--------------------------------------------------------------------------
| Agência PSI — Lembretes automáticos de sessão (CRM Grupo 2.4)
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useTenantStore } from '@/stores/tenantStore';
import { useSessionReminders } from '@/composables/useSessionReminders';

const toast = useToast();
const tenantStore = useTenantStore();
const api = useSessionReminders();

const VARIABLES = [
    { key: '{{nome_paciente}}', label: 'Nome do paciente' },
    { key: '{{data_sessao}}', label: 'Data (ex: 22 de abril)' },
    { key: '{{hora_sessao}}', label: 'Hora (ex: 14:30)' },
    { key: '{{modalidade}}', label: 'Online / presencial' },
    { key: '{{nome_clinica}}', label: 'Nome da clínica' }
];

const template24Ref = ref(null);
const template2Ref = ref(null);

function insertVariable(field, variable) {
    const el = field === '24h' ? template24Ref.value?.$el?.querySelector('textarea') : template2Ref.value?.$el?.querySelector('textarea');
    if (!el) return;
    const start = el.selectionStart ?? 0;
    const end = el.selectionEnd ?? 0;
    const key = field === '24h' ? 'template_24h' : 'template_2h';
    const before = api.settings.value[key].slice(0, start);
    const after = api.settings.value[key].slice(end);
    api.settings.value[key] = before + variable + after;
    setTimeout(() => {
        el.focus();
        const pos = start + variable.length;
        el.setSelectionRange(pos, pos);
    }, 10);
}

async function onSave() {
    const res = await api.save();
    if (res.ok) toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
    else toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
}

async function onRunNow() {
    const res = await api.runNow();
    if (res.ok) {
        const s = res.stats || {};
        const sent = s.sent || 0;
        const considered = s.considered || 0;
        const skippedTotal = Object.values(s.skipped || {}).reduce((a, b) => a + b, 0);
        toast.add({
            severity: sent > 0 ? 'success' : 'info',
            summary: `Execução concluída`,
            detail: `Considerados: ${considered} · Enviados: ${sent} · Pulados: ${skippedTotal}`,
            life: 5000
        });
        await api.load();
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

// Preview renderizado
const previewVars = {
    nome_paciente: 'Maria Silva',
    data_sessao: '22 de abril',
    hora_sessao: '14:30',
    modalidade: 'presencial',
    nome_clinica: 'Clínica Exemplo'
};

function renderPreview(tpl) {
    return String(tpl || '')
        .replaceAll('{{nome_paciente}}', previewVars.nome_paciente)
        .replaceAll('{{data_sessao}}', previewVars.data_sessao)
        .replaceAll('{{hora_sessao}}', previewVars.hora_sessao)
        .replaceAll('{{modalidade}}', previewVars.modalidade)
        .replaceAll('{{nome_clinica}}', previewVars.nome_clinica);
}

const preview24 = computed(() => renderPreview(api.settings.value.template_24h));
const preview2h = computed(() => renderPreview(api.settings.value.template_2h));

// Stats
const recentSent = computed(() => api.recentLogs.value.filter((l) => l.provider !== 'skipped').length);
const recentSkipped = computed(() => api.recentLogs.value.filter((l) => l.provider === 'skipped').length);

function fmtDate(iso) {
    if (!iso) return '';
    return new Date(iso).toLocaleString('pt-BR', {
        day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'
    });
}

function formatPhone(p) {
    const s = String(p || '').replace(/\D/g, '');
    if (s.length === 13 && s.startsWith('55')) return `(${s.slice(2, 4)}) ${s.slice(4, 9)}-${s.slice(9)}`;
    return p;
}

onMounted(() => { api.load(); });
watch(() => tenantStore.activeTenantId, () => { api.load(); });
</script>

<template>
    <Teleport to="#cfg-page-actions" defer>
        <Button
            label="Testar agora"
            icon="pi pi-bolt"
            severity="secondary"
            outlined
            size="small"
            class="rounded-full"
            :loading="api.saving.value"
            v-tooltip.bottom="'Roda o processo manualmente (útil pra testar ou fazer catch-up)'"
            @click="onRunNow"
        />
        <Button
            label="Salvar"
            icon="pi pi-check"
            size="small"
            class="rounded-full"
            :loading="api.saving.value"
            :disabled="api.loading.value"
            @click="onSave"
        />
        <Button
            icon="pi pi-refresh"
            severity="secondary"
            outlined
            class="h-9 w-9 rounded-full"
            :loading="api.loading.value"
            v-tooltip.bottom="'Recarregar'"
            @click="api.load()"
        />
    </Teleport>

    <div class="flex flex-col gap-4">
        <!-- Info -->
        <div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
            <i class="pi pi-info-circle text-sky-500 mt-0.5" />
            <div>
                <strong>Como funciona:</strong> a cada 15 minutos o sistema verifica sessões agendadas que estão chegando em
                <strong>24h ± 15min</strong> ou <strong>2h ± 15min</strong>, e envia WhatsApp pro paciente usando o canal ativo.
                Respeita opt-out (LGPD), quiet hours, e só envia uma vez por sessão+tipo.
                <br/>
                <strong>Pré-requisito:</strong> WhatsApp ativo (Oficial AgenciaPSI ou Pessoal) + paciente com telefone cadastrado.
            </div>
        </div>

        <!-- Toggle principal + stats -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
            <div class="flex items-center gap-3 flex-wrap">
                <label class="flex items-center gap-2 cursor-pointer">
                    <ToggleSwitch v-model="api.settings.value.enabled" />
                    <span class="text-sm font-semibold">
                        {{ api.settings.value.enabled ? 'Lembretes ativados' : 'Lembretes desativados' }}
                    </span>
                </label>
            </div>

            <div class="grid grid-cols-2 gap-3">
                <div class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
                    <div class="text-[1.35rem] font-bold leading-none text-green-500">{{ recentSent }}</div>
                    <div class="text-xs text-[var(--text-color-secondary)]">Enviados (últimos 30)</div>
                </div>
                <div class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)]">
                    <div class="text-[1.35rem] font-bold leading-none text-slate-500">{{ recentSkipped }}</div>
                    <div class="text-xs text-[var(--text-color-secondary)]">Pulados (opt-out, duplicata, etc)</div>
                </div>
            </div>
        </div>

        <!-- Lead times + templates -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-4">
            <div class="flex items-center gap-2">
                <i class="pi pi-clock text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Lembretes a enviar</span>
            </div>

            <!-- 24h -->
            <div class="flex flex-col gap-2">
                <div class="flex items-center gap-2">
                    <ToggleSwitch v-model="api.settings.value.send_24h" :disabled="!api.settings.value.enabled" />
                    <span class="text-sm font-semibold">24h antes da sessão</span>
                </div>
                <div v-if="api.settings.value.send_24h" class="flex flex-col gap-2 pl-10">
                    <div class="flex flex-wrap gap-1">
                        <Button
                            v-for="v in VARIABLES"
                            :key="v.key"
                            :label="v.key"
                            size="small"
                            severity="secondary"
                            outlined
                            class="!text-[0.7rem] !py-0.5 !px-1.5 font-mono"
                            :disabled="!api.settings.value.enabled"
                            v-tooltip.top="v.label"
                            @click="insertVariable('24h', v.key)"
                        />
                    </div>
                    <Textarea
                        ref="template24Ref"
                        v-model="api.settings.value.template_24h"
                        rows="3"
                        autoResize
                        class="w-full text-sm"
                        :maxlength="2000"
                        :disabled="!api.settings.value.enabled"
                    />
                    <div class="text-xs text-[var(--text-color-secondary)] p-2 rounded bg-[var(--surface-ground)] italic">
                        <strong class="not-italic">Preview:</strong> {{ preview24 }}
                    </div>
                </div>
            </div>

            <!-- 2h -->
            <div class="flex flex-col gap-2">
                <div class="flex items-center gap-2">
                    <ToggleSwitch v-model="api.settings.value.send_2h" :disabled="!api.settings.value.enabled" />
                    <span class="text-sm font-semibold">2h antes da sessão</span>
                </div>
                <div v-if="api.settings.value.send_2h" class="flex flex-col gap-2 pl-10">
                    <div class="flex flex-wrap gap-1">
                        <Button
                            v-for="v in VARIABLES"
                            :key="v.key"
                            :label="v.key"
                            size="small"
                            severity="secondary"
                            outlined
                            class="!text-[0.7rem] !py-0.5 !px-1.5 font-mono"
                            :disabled="!api.settings.value.enabled"
                            v-tooltip.top="v.label"
                            @click="insertVariable('2h', v.key)"
                        />
                    </div>
                    <Textarea
                        ref="template2Ref"
                        v-model="api.settings.value.template_2h"
                        rows="3"
                        autoResize
                        class="w-full text-sm"
                        :maxlength="2000"
                        :disabled="!api.settings.value.enabled"
                    />
                    <div class="text-xs text-[var(--text-color-secondary)] p-2 rounded bg-[var(--surface-ground)] italic">
                        <strong class="not-italic">Preview:</strong> {{ preview2h }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Quiet hours + LGPD -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-4">
            <div class="flex items-center gap-2">
                <i class="pi pi-moon text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Horário silencioso & compliance</span>
            </div>

            <!-- Quiet hours -->
            <div class="flex flex-col gap-2">
                <div class="flex items-center gap-2">
                    <ToggleSwitch v-model="api.settings.value.quiet_hours_enabled" :disabled="!api.settings.value.enabled" />
                    <span class="text-sm font-semibold">Não enviar em horário silencioso</span>
                </div>
                <div v-if="api.settings.value.quiet_hours_enabled" class="flex items-center gap-2 pl-10 flex-wrap">
                    <span class="text-xs text-[var(--text-color-secondary)]">Das</span>
                    <input
                        type="time"
                        v-model="api.settings.value.quiet_hours_start"
                        class="text-sm px-2 py-1 rounded border border-[var(--surface-border)] bg-[var(--surface-card)]"
                        :disabled="!api.settings.value.enabled"
                    />
                    <span class="text-xs text-[var(--text-color-secondary)]">até</span>
                    <input
                        type="time"
                        v-model="api.settings.value.quiet_hours_end"
                        class="text-sm px-2 py-1 rounded border border-[var(--surface-border)] bg-[var(--surface-card)]"
                        :disabled="!api.settings.value.enabled"
                    />
                    <span class="text-xs text-[var(--text-color-secondary)] italic">(fuso São Paulo)</span>
                </div>
                <div class="text-xs text-[var(--text-color-secondary)] pl-10">
                    Sessões que caem dentro do horário silencioso não disparam o lembrete — mesmo que "24h/2h antes" batam nessa janela.
                </div>
            </div>

            <!-- Opt-out -->
            <div class="flex flex-col gap-2 pt-2 border-t border-[var(--surface-border)]">
                <div class="flex items-center gap-2">
                    <ToggleSwitch v-model="api.settings.value.respect_opt_out" :disabled="!api.settings.value.enabled" />
                    <span class="text-sm font-semibold">Respeitar opt-out (LGPD)</span>
                </div>
                <div class="text-xs text-[var(--text-color-secondary)] pl-10">
                    Pacientes que enviaram "PARAR" não recebem lembretes. <strong>Recomendado manter ativado</strong>
                    — LGPD Art. 18 §2 (direito de oposição). Desligar só com base legal específica.
                </div>
            </div>
        </div>

        <!-- Log recente -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-3">
            <div class="flex items-center gap-2">
                <i class="pi pi-history text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Histórico recente (30 últimos)</span>
            </div>

            <div v-if="api.loading.value" class="flex flex-col gap-1.5">
                <Skeleton v-for="n in 4" :key="n" height="2.5rem" class="rounded-md" />
            </div>

            <div v-else-if="!api.recentLogs.value.length" class="text-xs text-[var(--text-color-secondary)] italic text-center py-4">
                Nenhum lembrete processado ainda. Clique em "Testar agora" pra executar manualmente.
            </div>

            <div v-else class="flex flex-col gap-1 max-h-[360px] overflow-y-auto">
                <div
                    v-for="log in api.recentLogs.value"
                    :key="log.id"
                    class="flex items-center gap-2 p-2 rounded-md border text-xs"
                    :class="log.provider === 'skipped'
                        ? 'border-[var(--surface-border)] bg-[var(--surface-ground)] opacity-80'
                        : 'border-green-500/25 bg-green-500/5'"
                >
                    <i
                        class="pi shrink-0"
                        :class="log.provider === 'skipped' ? 'pi-forward text-[var(--text-color-secondary)]' : 'pi-send text-green-500'"
                    />
                    <span class="font-semibold text-[0.7rem] uppercase px-1.5 py-px rounded shrink-0" :class="log.reminder_type === '24h' ? 'bg-indigo-500/10 text-indigo-500' : 'bg-amber-500/10 text-amber-500'">
                        {{ log.reminder_type }}
                    </span>
                    <span v-if="log.to_phone" class="font-mono">{{ formatPhone(log.to_phone) }}</span>
                    <span v-if="log.provider === 'skipped'" class="italic text-[var(--text-color-secondary)]">
                        {{ log.skip_reason }}
                    </span>
                    <span v-else class="text-green-600">enviado</span>
                    <span class="ml-auto text-[var(--text-color-secondary)]">{{ fmtDate(log.sent_at) }}</span>
                </div>
            </div>
        </div>
    </div>
</template>
