<!--
|--------------------------------------------------------------------------
| Agência PSI — Tags de Conversa (configurações)
|--------------------------------------------------------------------------
| CRUD de tags custom. Tags do sistema aparecem em modo leitura.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import { supabase } from '@/lib/supabase/client';
import { tenantDb } from '@/lib/supabase/tenantClient';
import { useTenantStore } from '@/stores/tenantStore';
import { useConversationTags } from '@/composables/useConversationTags';

const toast = useToast();
const confirm = useConfirm();
const tenantStore = useTenantStore();
const tagsApi = useConversationTags();

// ── Usage count (quantas threads usam cada tag) ──────────────
const usageByTag = ref({}); // { [tagId]: count }

async function loadUsage() {
    const tenantId = tenantStore.activeTenantId;
    if (!tenantId) {
        usageByTag.value = {};
        return;
    }
    try {
        const { data, error } = await tenantDb().from('conversation_thread_tags')
            .select('tag_id')
            ;
        if (error) throw error;
        const counts = {};
        for (const row of data || []) {
            counts[row.tag_id] = (counts[row.tag_id] || 0) + 1;
        }
        usageByTag.value = counts;
    } catch (e) {
        console.error('[ConfiguracoesConversasTags] loadUsage:', e?.message);
        usageByTag.value = {};
    }
}

async function refresh() {
    await Promise.all([tagsApi.loadAllTags(), loadUsage()]);
}

// ── Quick stats ─────────────────────────────────────────────
const quickStats = computed(() => {
    const all = tagsApi.allTags.value || [];
    const system = all.filter((t) => t.is_system).length;
    const custom = all.filter((t) => !t.is_system).length;
    const emUso = Object.keys(usageByTag.value).length;
    return [
        { label: 'Total de tags', value: all.length, cls: '' },
        { label: 'Sistema', value: system, cls: '' },
        { label: 'Minhas tags', value: custom, cls: custom > 0 ? 'qs-ok' : '' },
        { label: 'Em uso', value: emUso, cls: emUso > 0 ? 'qs-ok' : '' }
    ];
});

// ── Dialog create/edit ──────────────────────────────────────
const presetColors = [
    '#ef4444', '#f97316', '#f59e0b', '#eab308',
    '#84cc16', '#22c55e', '#14b8a6', '#06b6d4',
    '#0ea5e9', '#6366f1', '#8b5cf6', '#a855f7',
    '#ec4899', '#64748b', '#292524'
];

const presetIcons = [
    { icon: 'pi pi-tag', label: 'Tag' },
    { icon: 'pi pi-exclamation-triangle', label: 'Alerta' },
    { icon: 'pi pi-exclamation-circle', label: 'Exclamação' },
    { icon: 'pi pi-info-circle', label: 'Info' },
    { icon: 'pi pi-check-circle', label: 'Check' },
    { icon: 'pi pi-star', label: 'Estrela' },
    { icon: 'pi pi-heart', label: 'Coração' },
    { icon: 'pi pi-flag', label: 'Bandeira' },
    { icon: 'pi pi-bookmark', label: 'Marcador' },
    { icon: 'pi pi-user', label: 'Usuário' },
    { icon: 'pi pi-user-plus', label: 'Novo usuário' },
    { icon: 'pi pi-users', label: 'Grupo' },
    { icon: 'pi pi-calendar', label: 'Calendário' },
    { icon: 'pi pi-calendar-times', label: 'Calendário cancelado' },
    { icon: 'pi pi-clock', label: 'Relógio' },
    { icon: 'pi pi-phone', label: 'Telefone' },
    { icon: 'pi pi-comment', label: 'Balão' },
    { icon: 'pi pi-whatsapp', label: 'WhatsApp' },
    { icon: 'pi pi-envelope', label: 'Envelope' },
    { icon: 'pi pi-send', label: 'Enviar' },
    { icon: 'pi pi-reply', label: 'Responder' },
    { icon: 'pi pi-bolt', label: 'Raio' },
    { icon: 'pi pi-dollar', label: 'Dinheiro' },
    { icon: 'pi pi-shield', label: 'Escudo' }
];

const dlg = reactive({
    open: false,
    mode: 'create',
    id: '',
    name: '',
    color: '#6366f1',
    icon: 'pi pi-tag'
});

function openCreate() {
    Object.assign(dlg, {
        open: true,
        mode: 'create',
        id: '',
        name: '',
        color: '#6366f1',
        icon: 'pi pi-tag'
    });
}

function openEdit(tag) {
    Object.assign(dlg, {
        open: true,
        mode: 'edit',
        id: tag.id,
        name: tag.name,
        color: tag.color,
        icon: tag.icon || 'pi pi-tag'
    });
}

async function saveTag() {
    const clean = (dlg.name || '').trim();
    if (!clean) {
        toast.add({ severity: 'warn', summary: 'Nome obrigatório', life: 2500 });
        return;
    }
    let res;
    if (dlg.mode === 'create') {
        res = await tagsApi.createCustomTag({ name: clean, color: dlg.color, icon: dlg.icon });
    } else {
        res = await tagsApi.updateCustomTag(dlg.id, { name: clean, color: dlg.color, icon: dlg.icon });
    }
    if (res.ok) {
        toast.add({ severity: 'success', summary: dlg.mode === 'create' ? 'Tag criada' : 'Tag atualizada', life: 2000 });
        dlg.open = false;
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error || 'Falha ao salvar', life: 3500 });
    }
}

function confirmDelete(tag) {
    const usage = usageByTag.value[tag.id] || 0;
    const msg = usage > 0
        ? `A tag "${tag.name}" está aplicada em ${usage} conversa${usage > 1 ? 's' : ''}. Ao remover, ela sai de todas. Continuar?`
        : `Remover a tag "${tag.name}"?`;
    confirm.require({
        message: msg,
        header: 'Remover tag',
        icon: 'pi pi-exclamation-triangle',
        acceptLabel: 'Remover',
        rejectLabel: 'Cancelar',
        acceptClass: 'p-button-danger',
        accept: async () => {
            const res = await tagsApi.deleteCustomTag(tag.id);
            if (res.ok) {
                await loadUsage();
                toast.add({ severity: 'success', summary: 'Tag removida', life: 2000 });
            } else {
                toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
            }
        }
    });
}

// ── Lifecycle ────────────────────────────────────────────────
onMounted(() => { refresh(); });

watch(() => tenantStore.activeTenantId, () => { refresh(); });
</script>

<template>
    <ConfirmDialog />

    <!-- Botões teleportados pro header do ConfiguracoesPage -->
    <Teleport to="#cfg-page-actions" defer>
        <Button
            label="Nova tag"
            icon="pi pi-plus"
            size="small"
            class="rounded-full"
            @click="openCreate"
        />
        <Button
            icon="pi pi-refresh"
            severity="secondary"
            outlined
            class="h-9 w-9 rounded-full"
            :loading="tagsApi.loading.value"
            v-tooltip.bottom="'Recarregar'"
            @click="refresh"
        />
    </Teleport>

    <div class="flex flex-col gap-3">

    <!-- Quick stats -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
        <template v-if="tagsApi.loading.value">
            <Skeleton v-for="n in 4" :key="n" height="3.5rem" class="rounded-md" />
        </template>
        <template v-else>
            <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-ok'
                        ? 'border-green-500/25 bg-green-500/5'
                        : 'border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)]'
                ]"
            >
                <div class="text-[1.35rem] font-bold leading-none" :class="s.cls === 'qs-ok' ? 'text-green-500' : 'text-[var(--text-color)]'">{{ s.value }}</div>
                <div class="text-[1rem] text-[var(--text-color-secondary)] opacity-75 truncate">{{ s.label }}</div>
            </div>
        </template>
    </div>

    <!-- Lista de tags -->
    <div>
        <div v-if="tagsApi.loading.value" class="flex flex-col gap-2">
            <Skeleton v-for="n in 6" :key="n" height="4rem" class="rounded-md" />
        </div>

        <div v-else-if="!tagsApi.allTags.value.length" class="flex flex-col items-center justify-center gap-2 py-12 text-center">
            <i class="pi pi-tag text-4xl text-[var(--text-color-secondary)] opacity-40" />
            <div class="text-[1rem] font-semibold">Nenhuma tag ainda</div>
            <Button label="Criar primeira tag" icon="pi pi-plus" size="small" @click="openCreate" />
        </div>

        <div v-else class="flex flex-col gap-2">
            <div
                v-for="tag in tagsApi.allTags.value"
                :key="tag.id"
                class="flex items-center gap-3 p-3 rounded-md border border-[var(--surface-border,#e2e8f0)] bg-[var(--surface-card,#fff)] hover:border-indigo-300/50 hover:shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all"
            >
                <!-- Preview da pill -->
                <span
                    class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[0.78rem] font-semibold shrink-0"
                    :style="{
                        background: tag.color + '20',
                        color: tag.color,
                        border: `1px solid ${tag.color}40`
                    }"
                >
                    <i v-if="tag.icon" :class="tag.icon" class="text-[0.7rem]" />
                    {{ tag.name }}
                </span>

                <div class="flex-1 min-w-0 flex flex-col">
                    <div class="flex items-center gap-2 flex-wrap">
                        <span class="text-xs font-mono text-[var(--text-color-secondary)]">{{ tag.slug }}</span>
                        <span
                            v-if="tag.is_system"
                            class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase tracking-wide bg-slate-500/10 text-slate-500"
                        >
                            Sistema
                        </span>
                        <span
                            v-else
                            class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase tracking-wide bg-indigo-500/10 text-indigo-500"
                        >
                            Custom
                        </span>
                    </div>
                    <div class="text-xs text-[var(--text-color-secondary)] mt-0.5">
                        <span v-if="usageByTag[tag.id]">
                            Em {{ usageByTag[tag.id] }} conversa{{ usageByTag[tag.id] > 1 ? 's' : '' }}
                        </span>
                        <span v-else class="italic opacity-60">Não utilizada</span>
                    </div>
                </div>

                <div class="flex items-center gap-1 shrink-0">
                    <Button
                        v-if="!tag.is_system"
                        icon="pi pi-pencil"
                        severity="secondary"
                        outlined
                        class="h-8 w-8 rounded-full"
                        v-tooltip.top="'Editar'"
                        :disabled="tagsApi.saving.value"
                        @click="openEdit(tag)"
                    />
                    <Button
                        v-if="!tag.is_system"
                        icon="pi pi-trash"
                        severity="danger"
                        outlined
                        class="h-8 w-8 rounded-full"
                        v-tooltip.top="'Remover'"
                        :disabled="tagsApi.saving.value"
                        @click="confirmDelete(tag)"
                    />
                    <span v-if="tag.is_system" class="text-[0.7rem] text-[var(--text-color-secondary)] italic opacity-60 px-2">
                        bloqueada
                    </span>
                </div>
            </div>
        </div>
    </div>

    </div><!-- /flex flex-col gap-3 wrapper -->

    <!-- Dialog create/edit -->
    <Dialog
        v-model:visible="dlg.open"
        :header="dlg.mode === 'create' ? 'Nova tag' : 'Editar tag'"
        modal
        :style="{ width: 'min(460px, 95vw)' }"
        :closable="!tagsApi.saving.value"
    >
        <div class="flex flex-col gap-3">
            <!-- Preview -->
            <div class="flex items-center justify-center py-3 bg-[var(--surface-ground)] rounded-md">
                <span
                    class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold"
                    :style="{
                        background: dlg.color + '20',
                        color: dlg.color,
                        border: `1px solid ${dlg.color}40`
                    }"
                >
                    <i v-if="dlg.icon" :class="dlg.icon" class="text-xs" />
                    {{ dlg.name.trim() || 'Preview' }}
                </span>
            </div>

            <!-- Nome -->
            <div>
                <label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Nome</label>
                <InputText v-model="dlg.name" placeholder="Ex: Aguardando confirmação" :maxlength="40" class="w-full" @keydown.enter="saveTag" />
            </div>

            <!-- Cor -->
            <div>
                <label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Cor</label>
                <div class="flex items-center flex-wrap gap-1.5">
                    <button
                        v-for="c in presetColors"
                        :key="c"
                        type="button"
                        class="w-7 h-7 rounded-full border-2 transition-transform cursor-pointer"
                        :class="dlg.color === c ? 'border-[var(--text-color)] scale-110' : 'border-transparent hover:scale-105'"
                        :style="{ background: c }"
                        :aria-label="c"
                        @click="dlg.color = c"
                    />
                    <input
                        type="color"
                        v-model="dlg.color"
                        class="w-7 h-7 rounded-full border-0 cursor-pointer"
                        aria-label="Cor personalizada"
                    />
                </div>
            </div>

            <!-- Ícone -->
            <div>
                <label class="block text-xs font-semibold text-[var(--text-color-secondary)] mb-1">Ícone</label>
                <div class="grid grid-cols-8 gap-1 max-h-[180px] overflow-y-auto pr-1 border border-[var(--surface-border)] rounded-md p-2 bg-[var(--surface-ground)]">
                    <button
                        v-for="p in presetIcons"
                        :key="p.icon"
                        type="button"
                        class="w-9 h-9 rounded-md flex items-center justify-center bg-transparent border cursor-pointer transition-all hover:scale-105"
                        :class="dlg.icon === p.icon ? 'border-[var(--primary-color)] bg-[var(--primary-color)]/10 text-[var(--primary-color)]' : 'border-[var(--surface-border)] text-[var(--text-color-secondary)]'"
                        v-tooltip.top="p.label"
                        @click="dlg.icon = p.icon"
                    >
                        <i :class="p.icon" class="text-sm" />
                    </button>
                </div>
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" text :disabled="tagsApi.saving.value" @click="dlg.open = false" />
            <Button :label="dlg.mode === 'create' ? 'Criar' : 'Salvar'" :loading="tagsApi.saving.value" :disabled="!dlg.name.trim()" @click="saveTag" />
        </template>
    </Dialog>
</template>
