<!--
|--------------------------------------------------------------------------
| DevTestsTab.vue — Catálogo de suítes de teste (CRUD + drag-drop)
|--------------------------------------------------------------------------
| Responde "o que está testado?" sem rodar npm test. Cada linha é uma
| suíte (arquivo .spec.js, grupo de testes SQL ou plano manual).
-->
<script setup>
import { ref, computed, onMounted } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import ConfirmDialog from 'primevue/confirmdialog';
import DevDrawer from './components/DevDrawer.vue';
import DevField from './components/DevField.vue';
import { useDraggableList, reorderWithIndexes } from './composables/useDraggableList';

const toast = useToast();
const confirm = useConfirm();

const loading = ref(true);
const items = ref([]);
const filterArea = ref('all');
const filterStatus = ref('all');
const filterCategoria = ref('all');
const search = ref('');
const openRow = ref(null);

const drawerOpen = ref(false);
const saving = ref(false);
const editingId = ref(null);
const form = ref(emptyForm());

function emptyForm() {
    return {
        area: '',
        categoria: 'unit',
        titulo: '',
        arquivo: '',
        descricao: '',
        total_tests: 0,
        passing: 0,
        failing: 0,
        skipped: 0,
        cobertura_pct: null,
        status: 'ok',
        last_run_at: null,
        sessao_criacao: '',
        notas: '',
        tags: ''
    };
}

const STATUS_LABEL = {
    ok:         { label: 'OK',         color: '#10b981', bg: 'rgba(16,185,129,.12)',  icon: 'pi-check-circle' },
    falhando:   { label: 'Falhando',   color: '#ef4444', bg: 'rgba(239,68,68,.12)',   icon: 'pi-exclamation-triangle' },
    pendente:   { label: 'Pendente',   color: '#0ea5e9', bg: 'rgba(14,165,233,.12)',  icon: 'pi-hourglass' },
    obsoleto:   { label: 'Obsoleto',   color: '#94a3b8', bg: 'rgba(148,163,184,.12)', icon: 'pi-ban' },
    a_escrever: { label: 'A escrever', color: '#f59e0b', bg: 'rgba(245,158,11,.12)',  icon: 'pi-pencil' }
};

const CATEGORIA_OPTIONS = ['unit', 'integration', 'e2e', 'manual', 'a_escrever'];

const AREA_SUGGESTIONS = [
    'agenda', 'auth', 'router', 'session', 'stores', 'utils',
    'pacientes', 'financeiro', 'documentos', 'comunicacao',
    'saas-admin', 'database', 'rls', 'e2e'
];

async function load() {
    loading.value = true;
    try {
        const { data, error } = await supabase
            .from('dev_test_items')
            .select('*')
            .order('area')
            .order('ordem')
            .order('created_at', { ascending: false });
        if (error) throw error;
        items.value = data || [];
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
    } finally {
        loading.value = false;
    }
}

const areasList = computed(() => {
    const set = new Set();
    items.value.forEach((i) => i.area && set.add(i.area));
    AREA_SUGGESTIONS.forEach((a) => set.add(a));
    return Array.from(set).sort();
});

const itemsFiltered = computed(() => {
    let list = items.value;
    if (filterArea.value !== 'all') list = list.filter((i) => i.area === filterArea.value);
    if (filterStatus.value !== 'all') list = list.filter((i) => i.status === filterStatus.value);
    if (filterCategoria.value !== 'all') list = list.filter((i) => i.categoria === filterCategoria.value);
    if (search.value.trim()) {
        const q = search.value.toLowerCase();
        list = list.filter(
            (i) =>
                i.titulo.toLowerCase().includes(q) ||
                (i.descricao || '').toLowerCase().includes(q) ||
                (i.arquivo || '').toLowerCase().includes(q) ||
                (i.area || '').toLowerCase().includes(q) ||
                `t#${i.id}`.includes(q)
        );
    }
    return list;
});

const counts = computed(() => {
    const total = items.value.reduce((acc, i) => acc + (i.total_tests || 0), 0);
    const passing = items.value.reduce((acc, i) => acc + (i.passing || 0), 0);
    const failing = items.value.reduce((acc, i) => acc + (i.failing || 0), 0);
    return {
        suites: items.value.length,
        ok: items.value.filter((i) => i.status === 'ok').length,
        falhando: items.value.filter((i) => i.status === 'falhando').length,
        a_escrever: items.value.filter((i) => i.status === 'a_escrever').length,
        total,
        passing,
        failing
    };
});

function toggle(id) {
    openRow.value = openRow.value === id ? null : id;
}

function formatDateTime(iso) {
    if (!iso) return '—';
    const d = new Date(iso);
    return `${d.toLocaleDateString('pt-BR')} ${d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}`;
}

// ── CRUD ────────────────────────────────────────────────────────
function openNew() {
    editingId.value = null;
    form.value = emptyForm();
    if (filterArea.value !== 'all') form.value.area = filterArea.value;
    drawerOpen.value = true;
}

function openEdit(item) {
    editingId.value = item.id;
    form.value = {
        area: item.area || '',
        categoria: item.categoria || 'unit',
        titulo: item.titulo || '',
        arquivo: item.arquivo || '',
        descricao: item.descricao || '',
        total_tests: item.total_tests ?? 0,
        passing: item.passing ?? 0,
        failing: item.failing ?? 0,
        skipped: item.skipped ?? 0,
        cobertura_pct: item.cobertura_pct,
        status: item.status || 'ok',
        last_run_at: item.last_run_at ? item.last_run_at.substring(0, 16) : null,
        sessao_criacao: item.sessao_criacao || '',
        notas: item.notas || '',
        tags: (item.tags || []).join(', ')
    };
    drawerOpen.value = true;
}

async function save() {
    if (!form.value.titulo.trim()) {
        toast.add({ severity: 'warn', summary: 'Título obrigatório', life: 3000 });
        return;
    }
    if (!form.value.area.trim()) {
        toast.add({ severity: 'warn', summary: 'Área obrigatória', life: 3000 });
        return;
    }
    saving.value = true;
    try {
        const payload = {
            area: form.value.area.trim(),
            categoria: form.value.categoria.trim() || null,
            titulo: form.value.titulo.trim(),
            arquivo: form.value.arquivo.trim() || null,
            descricao: form.value.descricao.trim() || null,
            total_tests: Number(form.value.total_tests) || 0,
            passing: Number(form.value.passing) || 0,
            failing: Number(form.value.failing) || 0,
            skipped: Number(form.value.skipped) || 0,
            cobertura_pct: form.value.cobertura_pct !== '' && form.value.cobertura_pct !== null ? Number(form.value.cobertura_pct) : null,
            status: form.value.status,
            last_run_at: form.value.last_run_at || null,
            sessao_criacao: form.value.sessao_criacao.trim() || null,
            notas: form.value.notas.trim() || null,
            tags: form.value.tags
                ? form.value.tags.split(',').map((t) => t.trim()).filter(Boolean)
                : []
        };

        if (editingId.value) {
            const { error } = await supabase.from('dev_test_items').update(payload).eq('id', editingId.value);
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
        } else {
            payload.ordem = (items.value.filter((i) => i.area === payload.area).length || 0) + 1;
            const { error } = await supabase.from('dev_test_items').insert(payload);
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Criado', life: 2000 });
        }
        drawerOpen.value = false;
        await load();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 4000 });
    } finally {
        saving.value = false;
    }
}

function askDelete() {
    if (!editingId.value) return;
    confirm.require({
        message: 'Tem certeza que quer excluir este item?',
        header: 'Confirmar exclusão',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        accept: async () => {
            try {
                const { error } = await supabase.from('dev_test_items').delete().eq('id', editingId.value);
                if (error) throw error;
                toast.add({ severity: 'success', summary: 'Excluído', life: 2000 });
                drawerOpen.value = false;
                await load();
            } catch (e) {
                toast.add({ severity: 'error', summary: 'Erro', detail: e.message, life: 4000 });
            }
        }
    });
}

// ── Drag & drop ───────────────────────────────────────────────────
async function handleReorder(fromIdx, toIdx) {
    const hasFilter = filterArea.value !== 'all' || filterStatus.value !== 'all' || filterCategoria.value !== 'all' || search.value.trim();
    if (hasFilter) {
        toast.add({
            severity: 'warn',
            summary: 'Limpe os filtros pra reordenar',
            detail: 'Drag-drop só funciona com a lista completa.',
            life: 3500
        });
        return;
    }
    const before = items.value;
    items.value = reorderWithIndexes(before, fromIdx, toIdx);
    try {
        const updates = items.value.map((item) =>
            supabase.from('dev_test_items').update({ ordem: item.ordem }).eq('id', item.id)
        );
        await Promise.all(updates);
    } catch (e) {
        items.value = before;
        toast.add({ severity: 'error', summary: 'Erro ao reordenar', detail: e.message, life: 4000 });
    }
}

const drag = useDraggableList({ onReorder: handleReorder });

onMounted(load);
</script>

<template>
    <ConfirmDialog />

    <div v-if="loading" class="loading">
        <i class="pi pi-spin pi-spinner text-2xl text-indigo-500" />
    </div>

    <div v-else class="testes">
        <!-- Stats -->
        <div class="stats">
            <div class="stat">
                <span class="stat-num">{{ counts.suites }}</span>
                <span class="stat-lbl">suítes</span>
            </div>
            <div class="stat" style="--c: #10b981">
                <span class="stat-num">{{ counts.passing }}<small class="stat-sub">/{{ counts.total }}</small></span>
                <span class="stat-lbl">passing</span>
            </div>
            <div class="stat" style="--c: #ef4444">
                <span class="stat-num">{{ counts.failing }}</span>
                <span class="stat-lbl">falhando</span>
            </div>
            <div class="stat" style="--c: #f59e0b">
                <span class="stat-num">{{ counts.a_escrever }}</span>
                <span class="stat-lbl">a escrever</span>
            </div>
        </div>

        <!-- Toolbar -->
        <div class="toolbar">
            <input v-model="search" type="search" placeholder="Buscar (titulo, T#n, area)..." class="filter-search" />
            <select v-model="filterArea" class="filter-sel">
                <option value="all">Todas áreas</option>
                <option v-for="a in areasList" :key="a" :value="a">{{ a }}</option>
            </select>
            <select v-model="filterCategoria" class="filter-sel">
                <option value="all">Todas categorias</option>
                <option v-for="c in CATEGORIA_OPTIONS" :key="c" :value="c">{{ c }}</option>
            </select>
            <select v-model="filterStatus" class="filter-sel">
                <option value="all">Todos os status</option>
                <option value="ok">OK</option>
                <option value="falhando">Falhando</option>
                <option value="pendente">Pendente</option>
                <option value="a_escrever">A escrever</option>
                <option value="obsoleto">Obsoleto</option>
            </select>
            <button class="btn-primary" @click="openNew">
                <i class="pi pi-plus" /> Nova suíte
            </button>
        </div>

        <!-- Lista -->
        <div v-if="!itemsFiltered.length" class="empty">
            Nenhum item com os filtros atuais.
        </div>

        <div v-else class="list">
            <article
                v-for="(item, idx) in itemsFiltered"
                :key="item.id"
                :class="[
                    'test-item',
                    { open: openRow === item.id, dragging: drag.dragIdx.value === idx, 'drop-target': drag.overIdx.value === idx && drag.dragIdx.value !== idx }
                ]"
                draggable="true"
                @dragstart="drag.onDragStart($event, idx)"
                @dragover.prevent="drag.onDragOver($event, idx)"
                @drop="drag.onDrop($event, idx)"
                @dragend="drag.onDragEnd"
            >
                <header class="test-head">
                    <span class="drag-handle" title="Arrastar pra reordenar">
                        <i class="pi pi-bars" />
                    </span>
                    <i
                        :class="['pi', STATUS_LABEL[item.status]?.icon || 'pi-circle']"
                        :style="{ color: STATUS_LABEL[item.status]?.color }"
                    />
                    <div class="test-title-wrap" @click="toggle(item.id)">
                        <h4 class="test-title">
                            <span class="test-ref">T#{{ item.id }}</span>
                            <span class="test-area">{{ item.area }}</span>
                            {{ item.titulo }}
                        </h4>
                        <div class="test-meta">
                            <span v-if="item.categoria" class="test-cat">{{ item.categoria }}</span>
                            <span v-if="item.total_tests > 0" class="test-count">
                                <i class="pi pi-check text-emerald-500" /> {{ item.passing }}/{{ item.total_tests }}
                                <span v-if="item.failing > 0" class="text-red-500"> · {{ item.failing }} falhando</span>
                            </span>
                            <span v-if="item.arquivo" class="test-file">
                                <i class="pi pi-file text-xs" /> {{ item.arquivo }}
                            </span>
                        </div>
                    </div>
                    <span
                        class="test-status"
                        :style="{ color: STATUS_LABEL[item.status]?.color, background: STATUS_LABEL[item.status]?.bg }"
                    >{{ STATUS_LABEL[item.status]?.label }}</span>
                    <button class="btn-icon" @click="openEdit(item)" title="Editar">
                        <i class="pi pi-pencil" />
                    </button>
                    <i
                        :class="['pi pi-chevron-down test-chev', { open: openRow === item.id }]"
                        @click="toggle(item.id)"
                    />
                </header>

                <div v-if="openRow === item.id" class="test-body">
                    <div v-if="item.descricao" class="test-section">
                        <h5>Cobertura</h5>
                        <p>{{ item.descricao }}</p>
                    </div>
                    <div v-if="item.notas" class="test-section">
                        <h5>Notas</h5>
                        <p>{{ item.notas }}</p>
                    </div>
                    <div v-if="item.last_run_at || item.sessao_criacao" class="test-section">
                        <h5>Execução</h5>
                        <p>
                            <span v-if="item.last_run_at">Última execução: {{ formatDateTime(item.last_run_at) }}</span>
                            <span v-if="item.sessao_criacao" class="text-[var(--text-color-secondary)]">
                                <span v-if="item.last_run_at"> — </span>Criado na {{ item.sessao_criacao }}
                            </span>
                        </p>
                    </div>
                    <div v-if="item.cobertura_pct !== null" class="test-section">
                        <h5>Cobertura estimada</h5>
                        <p>{{ item.cobertura_pct }}%</p>
                    </div>
                    <div v-if="item.tags && item.tags.length" class="test-tags">
                        <span v-for="tag in item.tags" :key="tag" class="tag">#{{ tag }}</span>
                    </div>
                </div>
            </article>
        </div>

        <!-- Drawer -->
        <DevDrawer
            :open="drawerOpen"
            :title="editingId ? 'Editar suíte' : 'Nova suíte'"
            :subtitle="editingId ? `T#${editingId}` : 'Preencha os campos e salve'"
            :can-save="!!form.titulo.trim() && !!form.area.trim()"
            :saving="saving"
            :danger="!!editingId"
            @close="drawerOpen = false"
            @save="save"
            @delete="askDelete"
        >
            <div class="form-row">
                <DevField label="Área" required hint="Ex.: agenda, auth, pacientes, e2e">
                    <input v-model="form.area" list="area-suggestions-tests" placeholder="área" />
                    <datalist id="area-suggestions-tests">
                        <option v-for="a in AREA_SUGGESTIONS" :key="a" :value="a" />
                    </datalist>
                </DevField>

                <DevField label="Categoria">
                    <select v-model="form.categoria">
                        <option v-for="c in CATEGORIA_OPTIONS" :key="c" :value="c">{{ c }}</option>
                    </select>
                </DevField>
            </div>

            <DevField label="Título" required>
                <input v-model="form.titulo" placeholder="Ex.: useRecurrence — geração de ocorrências" />
            </DevField>

            <DevField label="Status">
                <select v-model="form.status">
                    <option value="ok">OK — todos passando</option>
                    <option value="falhando">Falhando</option>
                    <option value="pendente">Pendente</option>
                    <option value="a_escrever">A escrever</option>
                    <option value="obsoleto">Obsoleto</option>
                </select>
            </DevField>

            <DevField label="Arquivo" hint="src/features/agenda/.../__tests__/*.spec.js">
                <input v-model="form.arquivo" placeholder="Caminho do arquivo de teste" />
            </DevField>

            <DevField label="Cobertura (descrição)" hint="O que essa suíte cobre">
                <textarea v-model="form.descricao" rows="3" />
            </DevField>

            <div class="form-row-3">
                <DevField label="Total">
                    <input v-model.number="form.total_tests" type="number" min="0" />
                </DevField>
                <DevField label="Passing">
                    <input v-model.number="form.passing" type="number" min="0" />
                </DevField>
                <DevField label="Falhando">
                    <input v-model.number="form.failing" type="number" min="0" />
                </DevField>
            </div>

            <div class="form-row">
                <DevField label="Skipped">
                    <input v-model.number="form.skipped" type="number" min="0" />
                </DevField>
                <DevField label="Cobertura %">
                    <input v-model.number="form.cobertura_pct" type="number" min="0" max="100" step="0.01" />
                </DevField>
            </div>

            <DevField label="Última execução">
                <input v-model="form.last_run_at" type="datetime-local" />
            </DevField>

            <DevField label="Sessão de criação" hint="Ex.: Sessão 2 — agenda">
                <input v-model="form.sessao_criacao" />
            </DevField>

            <DevField label="Notas">
                <textarea v-model="form.notas" rows="3" />
            </DevField>

            <DevField label="Tags" hint="Separe por vírgula">
                <input v-model="form.tags" placeholder="tag1, tag2" />
            </DevField>
        </DevDrawer>
    </div>
</template>

<style scoped>
.loading { text-align: center; padding: 60px; }

.testes { display: flex; flex-direction: column; gap: 12px; }

.stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 10px;
}
.stat {
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border);
    border-left: 3px solid var(--c, var(--primary-color));
    border-radius: 8px;
    padding: 12px 14px;
    display: flex;
    flex-direction: column;
}
.stat-num { font-size: 22px; font-weight: 700; color: var(--text-color); line-height: 1; }
.stat-sub { font-size: 13px; font-weight: 500; color: var(--text-color-secondary); }
.stat-lbl { font-size: 11px; color: var(--text-color-secondary); margin-top: 4px; }

.toolbar { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.filter-search, .filter-sel {
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border);
    border-radius: 7px;
    padding: 7px 11px;
    font-size: 12px;
    color: var(--text-color);
    outline: none;
}
.filter-search { flex: 1; min-width: 220px; }
.filter-sel { min-width: 140px; cursor: pointer; }

.btn-primary {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 7px;
    padding: 8px 13px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    transition: opacity 0.15s;
}
.btn-primary:hover { opacity: 0.9; }

.list { display: flex; flex-direction: column; gap: 8px; }

.test-item {
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.15s;
}
.test-item:hover { border-color: color-mix(in srgb, var(--primary-color) 30%, var(--surface-border)); }
.test-item.dragging { opacity: 0.4; transform: scale(0.98); }
.test-item.drop-target { border-color: var(--primary-color); border-style: dashed; background: color-mix(in srgb, var(--primary-color) 5%, transparent); }

.test-head {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    user-select: none;
}

.drag-handle {
    display: grid;
    place-items: center;
    width: 22px;
    height: 22px;
    border-radius: 4px;
    color: var(--text-color-secondary);
    cursor: grab;
    flex-shrink: 0;
    opacity: 0.5;
    transition: opacity 0.15s;
}
.drag-handle:hover { opacity: 1; background: var(--surface-ground); }
.drag-handle:active { cursor: grabbing; }

.test-head > .pi:nth-child(2) { font-size: 16px; flex-shrink: 0; }

.test-title-wrap { flex: 1; min-width: 0; cursor: pointer; }
.test-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-color);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.test-ref {
    font-family: 'IBM Plex Mono', monospace;
    font-size: 10px;
    font-weight: 700;
    color: var(--text-color-secondary);
    background: var(--surface-ground);
    padding: 2px 7px;
    border-radius: 4px;
    user-select: all;
}
.test-area {
    font-family: 'IBM Plex Mono', monospace;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--primary-color);
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    padding: 2px 7px;
    border-radius: 4px;
}
.test-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    font-size: 11px;
    color: var(--text-color-secondary);
    margin-top: 3px;
}
.test-cat {
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
}
.test-count {
    font-family: 'IBM Plex Mono', monospace;
    display: flex;
    align-items: center;
    gap: 4px;
}
.test-file {
    font-family: 'IBM Plex Mono', monospace;
    display: flex;
    align-items: center;
    gap: 4px;
}

.test-status {
    font-size: 10px;
    font-weight: 700;
    padding: 3px 9px;
    border-radius: 10px;
    text-transform: uppercase;
    letter-spacing: 0.4px;
    white-space: nowrap;
}

.btn-icon {
    background: transparent;
    border: none;
    width: 28px;
    height: 28px;
    border-radius: 6px;
    color: var(--text-color-secondary);
    cursor: pointer;
    font-size: 12px;
    flex-shrink: 0;
    transition: all 0.15s;
}
.btn-icon:hover {
    background: var(--surface-ground);
    color: var(--primary-color);
}

.test-chev {
    font-size: 11px;
    color: var(--text-color-secondary);
    transition: transform 0.2s;
    cursor: pointer;
    padding: 8px;
}
.test-chev.open { transform: rotate(180deg); }

.test-body {
    padding: 0 14px 14px 42px;
    border-top: 1px solid var(--surface-border);
    padding-top: 12px;
}
.test-section { margin-bottom: 10px; }
.test-section h5 {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-color-secondary);
    margin-bottom: 4px;
}
.test-section p {
    font-size: 12px;
    line-height: 1.55;
    color: var(--text-color);
    margin: 0;
    white-space: pre-wrap;
}

.test-tags { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 8px; }
.tag {
    font-size: 10px;
    font-family: 'IBM Plex Mono', monospace;
    color: var(--primary-color);
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    padding: 2px 7px;
    border-radius: 4px;
}

.empty {
    text-align: center;
    padding: 40px;
    color: var(--text-color-secondary);
    background: var(--surface-card);
    border: 1px dashed var(--surface-border);
    border-radius: 10px;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}
.form-row-3 {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 10px;
}
</style>
