<!--
|--------------------------------------------------------------------------
| Agência PSI — Opt-outs do CRM WhatsApp (LGPD Art. 18 Sec.2)
|--------------------------------------------------------------------------
| Lista de números que pediram pra não receber mensagens automáticas.
| Configuração das palavras-chave de opt-out.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { useTenantStore } from '@/stores/tenantStore';
import { useConversationOptouts } from '@/composables/useConversationOptouts';

const toast = useToast();
const confirm = useConfirm();
const tenantStore = useTenantStore();
const api = useConversationOptouts();

const activeTab = ref(0);

// Dialog de adicionar manual
const dlg = reactive({ open: false, phone: '', notes: '' });

function openAddManual() {
    dlg.open = true;
    dlg.phone = '';
    dlg.notes = '';
}

async function saveManual() {
    const res = await api.addManual({ phone: dlg.phone, notes: dlg.notes.trim() || null });
    if (res.ok) {
        toast.add({ severity: 'success', summary: 'Opt-out adicionado', life: 2200 });
        dlg.open = false;
    } else if (res.error === 'already_opted_out') {
        toast.add({ severity: 'warn', summary: 'Já existe', detail: 'Este número já está opted-out ativo.', life: 3500 });
    } else if (res.error === 'invalid_phone_format') {
        toast.add({ severity: 'error', summary: 'Telefone inválido', detail: 'Use formato DDD + número (11 dígitos).', life: 3500 });
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

function confirmRestore(optout) {
    const label = optout._patient_name || optout.phone;
    confirm.require({
        message: `Restaurar ${label}? A pessoa voltará a receber mensagens automáticas.`,
        header: 'Restaurar opt-out',
        icon: 'pi pi-undo',
        acceptLabel: 'Restaurar',
        rejectLabel: 'Cancelar',
        accept: async () => {
            const res = await api.restore(optout.id);
            if (res.ok) {
                toast.add({ severity: 'success', summary: 'Restaurado', life: 2000 });
            } else {
                toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
            }
        }
    });
}

// Keywords
const newKeyword = ref('');
async function addKw() {
    const res = await api.addKeyword(newKeyword.value);
    if (res.ok) {
        newKeyword.value = '';
        toast.add({ severity: 'success', summary: 'Keyword adicionada', life: 1800 });
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

async function onToggleKw(kw, enabled) {
    const res = await api.toggleKeyword(kw.id, enabled);
    if (!res.ok) toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
}

function confirmDeleteKw(kw) {
    confirm.require({
        message: `Remover keyword "${kw.keyword}"?`,
        header: 'Remover',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        acceptLabel: 'Remover',
        rejectLabel: 'Cancelar',
        accept: async () => {
            const res = await api.deleteKeyword(kw.id);
            if (res.ok) toast.add({ severity: 'success', summary: 'Removida', life: 1800 });
            else toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
        }
    });
}

// Helpers
function formatPhoneDisplay(phone) {
    const s = String(phone || '').replace(/\D/g, '');
    // 55 11 98765-4321
    if (s.length === 13 && s.startsWith('55')) {
        return `+55 (${s.slice(2, 4)}) ${s.slice(4, 9)}-${s.slice(9)}`;
    }
    if (s.length === 12 && s.startsWith('55')) {
        return `+55 (${s.slice(2, 4)}) ${s.slice(4, 8)}-${s.slice(8)}`;
    }
    return `+${s}`;
}

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

const quickStats = computed(() => [
    { label: 'Ativos', value: api.activeOptouts.value.length, cls: api.activeOptouts.value.length > 0 ? 'qs-warn' : '' },
    { label: 'Por keyword', value: api.activeOptouts.value.filter((o) => o.source === 'keyword').length, cls: '' },
    { label: 'Adicionados manual', value: api.activeOptouts.value.filter((o) => o.source === 'manual').length, cls: '' },
    { label: 'Histórico (restaurados)', value: api.historyOptouts.value.length, cls: '' }
]);

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

<template>
    <ConfirmDialog />

    <Teleport to="#cfg-page-actions" defer>
        <Button
            v-if="activeTab === 0"
            label="Adicionar manualmente"
            icon="pi pi-plus"
            size="small"
            class="rounded-full"
            @click="openAddManual"
        />
        <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 LGPD -->
        <div class="rounded-md border border-amber-500/25 bg-amber-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
            <i class="pi pi-shield text-amber-500 mt-0.5 text-base" />
            <div>
                <strong>LGPD — Direito de oposição (Art. 18, §2):</strong>
                quando o paciente envia "PARAR" (ou similar), o sistema bloqueia automaticamente envios de auto-reply, lembretes e outras mensagens automáticas.
                O terapeuta ainda pode escrever manualmente — a relação terapêutica existe.
                Pra voltar a receber, o paciente envia "VOLTAR".
            </div>
        </div>

        <!-- Quick stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
            <div
                v-for="s in quickStats"
                :key="s.label"
                class="flex flex-col gap-0.5 px-4 py-2.5 rounded-md border transition-colors"
                :class="s.cls === 'qs-warn' ? 'border-amber-500/25 bg-amber-500/5' : 'border-[var(--surface-border)] bg-[var(--surface-card)]'"
            >
                <div class="text-[1.35rem] font-bold leading-none" :class="s.cls === 'qs-warn' ? 'text-amber-500' : 'text-[var(--text-color)]'">{{ s.value }}</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
            </div>
        </div>

        <!-- Tabs -->
        <Tabs :value="activeTab" @update:value="activeTab = $event">
            <TabList>
                <Tab :value="0"><i class="pi pi-ban mr-2" />Opt-outs</Tab>
                <Tab :value="1"><i class="pi pi-key mr-2" />Palavras-chave</Tab>
            </TabList>

            <TabPanels>
                <!-- Tab 0: Lista de opt-outs -->
                <TabPanel :value="0">
                    <div v-if="api.loading.value" class="flex flex-col gap-2 pt-3">
                        <Skeleton v-for="n in 5" :key="n" height="3.5rem" class="rounded-md" />
                    </div>

                    <div v-else-if="!api.optouts.value.length" class="flex flex-col items-center justify-center gap-2 py-12 text-center">
                        <i class="pi pi-check-circle text-4xl text-green-500 opacity-40" />
                        <div class="text-[1rem] font-semibold">Nenhum opt-out ainda</div>
                        <div class="text-sm text-[var(--text-color-secondary)]">Quando um paciente enviar "PARAR" ou similar, aparece aqui.</div>
                    </div>

                    <div v-else class="flex flex-col gap-2 pt-3">
                        <div
                            v-for="o in api.optouts.value"
                            :key="o.id"
                            class="flex items-center gap-3 p-3 rounded-md border transition-all"
                            :class="o.opted_back_in_at
                                ? 'border-[var(--surface-border)] bg-[var(--surface-ground)] opacity-70'
                                : 'border-amber-500/30 bg-amber-500/5'"
                        >
                            <i
                                class="pi text-lg shrink-0"
                                :class="o.opted_back_in_at ? 'pi-check-circle text-green-500' : 'pi-ban text-amber-500'"
                            />

                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <span class="font-semibold text-[var(--text-color)] truncate">
                                        {{ o._patient_name || formatPhoneDisplay(o.phone) }}
                                    </span>
                                    <span
                                        class="inline-flex items-center px-1.5 py-px rounded text-[0.62rem] font-bold uppercase"
                                        :class="o.source === 'keyword'
                                            ? 'bg-indigo-500/10 text-indigo-500'
                                            : 'bg-slate-500/10 text-slate-500'"
                                    >
                                        {{ o.source === 'keyword' ? `Keyword: ${o.keyword_matched}` : 'Manual' }}
                                    </span>
                                    <span v-if="o.opted_back_in_at" class="inline-flex items-center px-1.5 py-px rounded text-[0.62rem] font-bold uppercase bg-green-500/10 text-green-500">
                                        Restaurado
                                    </span>
                                </div>
                                <div class="text-xs text-[var(--text-color-secondary)] mt-0.5 flex items-center gap-2 flex-wrap">
                                    <span v-if="o._patient_name">{{ formatPhoneDisplay(o.phone) }}</span>
                                    <span>·</span>
                                    <span>{{ formatDate(o.opted_out_at) }}</span>
                                    <span v-if="o.opted_back_in_at">· restaurado em {{ formatDate(o.opted_back_in_at) }}</span>
                                </div>
                                <div v-if="o.original_message" class="text-xs text-[var(--text-color-secondary)] italic mt-1 truncate" :title="o.original_message">
                                    "{{ o.original_message }}"
                                </div>
                                <div v-if="o.notes" class="text-xs text-[var(--text-color)] mt-1">{{ o.notes }}</div>
                            </div>

                            <div class="shrink-0">
                                <Button
                                    v-if="!o.opted_back_in_at"
                                    label="Restaurar"
                                    icon="pi pi-undo"
                                    size="small"
                                    severity="secondary"
                                    outlined
                                    class="rounded-full"
                                    :loading="api.saving.value"
                                    @click="confirmRestore(o)"
                                />
                            </div>
                        </div>
                    </div>
                </TabPanel>

                <!-- Tab 1: Keywords -->
                <TabPanel :value="1">
                    <div class="flex flex-col gap-3 pt-3">
                        <!-- Add -->
                        <div class="flex gap-2 items-center">
                            <InputText
                                v-model="newKeyword"
                                placeholder="Adicionar palavra-chave (ex: não quero receber)"
                                class="flex-1"
                                :maxlength="100"
                                @keyup.enter="addKw"
                            />
                            <Button
                                label="Adicionar"
                                icon="pi pi-plus"
                                :loading="api.saving.value"
                                :disabled="!newKeyword.trim()"
                                @click="addKw"
                            />
                        </div>

                        <!-- Lista -->
                        <div v-if="api.loading.value" class="flex flex-col gap-2">
                            <Skeleton v-for="n in 5" :key="n" height="3rem" class="rounded-md" />
                        </div>

                        <div v-else-if="!api.keywords.value.length" class="text-sm text-[var(--text-color-secondary)] italic text-center py-6">
                            Nenhuma palavra-chave ainda.
                        </div>

                        <div v-else class="flex flex-col gap-1.5">
                            <div
                                v-for="kw in api.keywords.value"
                                :key="kw.id"
                                class="flex items-center gap-3 p-2.5 rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)]"
                            >
                                <i class="pi pi-key text-sm shrink-0" :class="kw.enabled ? 'text-[var(--primary-color)]' : 'text-[var(--text-color-secondary)] opacity-40'" />

                                <span class="font-mono text-sm flex-1" :class="!kw.enabled ? 'opacity-50 line-through' : ''">{{ kw.keyword }}</span>

                                <span
                                    class="inline-flex items-center px-1.5 py-px rounded text-[0.6rem] font-bold uppercase shrink-0"
                                    :class="kw.is_system ? 'bg-slate-500/10 text-slate-500' : 'bg-indigo-500/10 text-indigo-500'"
                                >
                                    {{ kw.is_system ? 'Sistema' : 'Custom' }}
                                </span>

                                <ToggleSwitch
                                    :modelValue="kw.enabled"
                                    @update:modelValue="(v) => onToggleKw(kw, v)"
                                    :disabled="api.saving.value"
                                />

                                <Button
                                    v-if="!kw.is_system"
                                    icon="pi pi-trash"
                                    severity="danger"
                                    text
                                    class="h-8 w-8"
                                    v-tooltip.top="'Remover'"
                                    :disabled="api.saving.value"
                                    @click="confirmDeleteKw(kw)"
                                />
                            </div>
                        </div>

                        <div class="text-xs text-[var(--text-color-secondary)] italic">
                            Palavras-chave do sistema não podem ser removidas, mas podem ser desabilitadas.
                            Match é case-insensitive e ignora acentos. Exemplo: "PARAR", "parar", "PARÁR" todos funcionam.
                        </div>
                    </div>
                </TabPanel>
            </TabPanels>
        </Tabs>
    </div>

    <!-- Dialog adicionar manual -->
    <Dialog
        v-model:visible="dlg.open"
        header="Adicionar opt-out manualmente"
        modal
        :style="{ width: 'min(440px, 95vw)' }"
        :closable="!api.saving.value"
    >
        <div class="flex flex-col gap-3">
            <div>
                <label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Telefone (com DDD)</label>
                <InputText
                    v-model="dlg.phone"
                    placeholder="11987654321"
                    class="w-full"
                    @keydown.enter="saveManual"
                />
                <div class="text-[0.7rem] text-[var(--text-color-secondary)] mt-1">
                    Só dígitos. DDI 55 é adicionado automaticamente se faltar.
                </div>
            </div>

            <div>
                <label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Motivo (opcional)</label>
                <Textarea
                    v-model="dlg.notes"
                    rows="2"
                    autoResize
                    class="w-full"
                    :maxlength="500"
                    placeholder="Ex: paciente pediu por telefone pra parar de receber"
                />
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" text :disabled="api.saving.value" @click="dlg.open = false" />
            <Button label="Adicionar" :loading="api.saving.value" :disabled="!dlg.phone.trim()" @click="saveManual" />
        </template>
    </Dialog>
</template>
