<!--
|--------------------------------------------------------------------------
| DevAuditoriaTab.vue — Bugs/débitos técnicos (CRUD + drag-drop)
|--------------------------------------------------------------------------
-->
<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 filterStatus = ref('all');
const filterSev = ref('all');
const search = ref('');
const openRow = ref(null);

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

function emptyForm() {
    return {
        categoria: '',
        titulo: '',
        descricao_problema: '',
        solucao: '',
        severidade: 'medio',
        status: 'aberto',
        resolvido_em: null,
        sessao_resolucao: '',
        arquivo_afetado: '',
        tags: ''
    };
}

const STATUS_LABEL = {
    aberto: { label: 'Aberto', color: '#ef4444', bg: 'rgba(239,68,68,.12)', icon: 'pi-exclamation-circle' },
    em_analise: { label: 'Em análise', color: '#f59e0b', bg: 'rgba(245,158,11,.12)', icon: 'pi-eye' },
    resolvido: { label: 'Resolvido', color: '#10b981', bg: 'rgba(16,185,129,.12)', icon: 'pi-check-circle' },
    wontfix: { label: "Won't fix", color: '#94a3b8', bg: 'rgba(148,163,184,.12)', icon: 'pi-ban' },
    duplicado: { label: 'Duplicado', color: '#94a3b8', bg: 'rgba(148,163,184,.12)', icon: 'pi-clone' }
};

const SEV_LABEL = {
    critico: { label: 'Crítico', color: '#dc2626' },
    alto: { label: 'Alto', color: '#f59e0b' },
    medio: { label: 'Médio', color: '#0ea5e9' },
    baixo: { label: 'Baixo', color: '#94a3b8' }
};

async function load() {
    loading.value = true;
    try {
        const { data, error } = await supabase
            .from('dev_auditoria_items')
            .select('*')
            .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 itemsFiltered = computed(() => {
    let list = items.value;
    if (filterStatus.value !== 'all') list = list.filter((i) => i.status === filterStatus.value);
    if (filterSev.value !== 'all') list = list.filter((i) => i.severidade === filterSev.value);
    if (search.value.trim()) {
        const q = search.value.toLowerCase();
        list = list.filter(
            (i) =>
                i.titulo.toLowerCase().includes(q) ||
                (i.descricao_problema || '').toLowerCase().includes(q) ||
                (i.categoria || '').toLowerCase().includes(q)
        );
    }
    return list;
});

const counts = computed(() => ({
    total: items.value.length,
    aberto: items.value.filter((i) => ['aberto', 'em_analise'].includes(i.status)).length,
    resolvido: items.value.filter((i) => i.status === 'resolvido').length,
    critico: items.value.filter((i) => i.severidade === 'critico' && ['aberto', 'em_analise'].includes(i.status)).length
}));

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

function formatDate(iso) {
    if (!iso) return '—';
    return new Date(iso).toLocaleDateString('pt-BR');
}

// ── CRUD ────────────────────────────────────────────────────────
function openNew() {
    editingId.value = null;
    form.value = emptyForm();
    drawerOpen.value = true;
}

function openEdit(item) {
    editingId.value = item.id;
    form.value = {
        categoria: item.categoria || '',
        titulo: item.titulo || '',
        descricao_problema: item.descricao_problema || '',
        solucao: item.solucao || '',
        severidade: item.severidade || 'medio',
        status: item.status || 'aberto',
        resolvido_em: item.resolvido_em || null,
        sessao_resolucao: item.sessao_resolucao || '',
        arquivo_afetado: item.arquivo_afetado || '',
        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;
    }
    saving.value = true;
    try {
        const payload = {
            categoria: form.value.categoria.trim() || null,
            titulo: form.value.titulo.trim(),
            descricao_problema: form.value.descricao_problema.trim() || null,
            solucao: form.value.solucao.trim() || null,
            severidade: form.value.severidade || null,
            status: form.value.status,
            resolvido_em: form.value.resolvido_em || null,
            sessao_resolucao: form.value.sessao_resolucao.trim() || null,
            arquivo_afetado: form.value.arquivo_afetado.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_auditoria_items').update(payload).eq('id', editingId.value);
            if (error) throw error;
            toast.add({ severity: 'success', summary: 'Salvo', life: 2000 });
        } else {
            payload.ordem = (items.value.length || 0) + 1;
            const { error } = await supabase.from('dev_auditoria_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_auditoria_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) {
    // Reordena apenas se não houver filtro ativo (senão os índices não batem com o DB)
    const hasFilter = filterStatus.value !== 'all' || filterSev.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_auditoria_items').update({ ordem: item.ordem }).eq('id', item.id)
        );
        await Promise.all(updates);
    } catch (e) {
        items.value = before; // rollback
        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="auditoria">
        <!-- Stats -->
        <div class="stats">
            <div class="stat">
                <span class="stat-num">{{ counts.total }}</span>
                <span class="stat-lbl">total</span>
            </div>
            <div class="stat" style="--c: #ef4444">
                <span class="stat-num">{{ counts.aberto }}</span>
                <span class="stat-lbl">em aberto</span>
            </div>
            <div class="stat" style="--c: #10b981">
                <span class="stat-num">{{ counts.resolvido }}</span>
                <span class="stat-lbl">resolvidos</span>
            </div>
            <div class="stat" style="--c: #dc2626">
                <span class="stat-num">{{ counts.critico }}</span>
                <span class="stat-lbl">críticos abertos</span>
            </div>
        </div>

        <!-- Toolbar -->
        <div class="toolbar">
            <input v-model="search" type="search" placeholder="Buscar bug/débito..." class="filter-search" />
            <select v-model="filterStatus" class="filter-sel">
                <option value="all">Todos os status</option>
                <option value="aberto">Aberto</option>
                <option value="em_analise">Em análise</option>
                <option value="resolvido">Resolvido</option>
                <option value="wontfix">Won't fix</option>
                <option value="duplicado">Duplicado</option>
            </select>
            <select v-model="filterSev" class="filter-sel">
                <option value="all">Todas severidades</option>
                <option value="critico">Crítico</option>
                <option value="alto">Alto</option>
                <option value="medio">Médio</option>
                <option value="baixo">Baixo</option>
            </select>
            <button class="btn-primary" @click="openNew">
                <i class="pi pi-plus" /> Novo item
            </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="[
                    'audit-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="audit-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="audit-title-wrap" @click="toggle(item.id)">
                        <h4 class="audit-title">
                            <span class="audit-ref">A#{{ item.id }}</span>
                            {{ item.titulo }}
                        </h4>
                        <div class="audit-meta">
                            <span v-if="item.categoria" class="audit-cat">{{ item.categoria }}</span>
                            <span v-if="item.severidade" :style="{ color: SEV_LABEL[item.severidade]?.color }">
                                {{ SEV_LABEL[item.severidade]?.label }}
                            </span>
                            <span v-if="item.arquivo_afetado" class="audit-file">
                                <i class="pi pi-file text-xs" /> {{ item.arquivo_afetado }}
                            </span>
                        </div>
                    </div>
                    <span
                        class="audit-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 audit-chev', { open: openRow === item.id }]"
                        @click="toggle(item.id)"
                    />
                </header>

                <div v-if="openRow === item.id" class="audit-body">
                    <div v-if="item.descricao_problema" class="audit-section">
                        <h5>Problema</h5>
                        <p>{{ item.descricao_problema }}</p>
                    </div>
                    <div v-if="item.solucao" class="audit-section">
                        <h5>Solução</h5>
                        <p>{{ item.solucao }}</p>
                    </div>
                    <div v-if="item.sessao_resolucao || item.resolvido_em" class="audit-section">
                        <h5>Resolução</h5>
                        <p>
                            <span v-if="item.sessao_resolucao">{{ item.sessao_resolucao }}</span>
                            <span v-if="item.resolvido_em" class="text-[var(--text-color-secondary)]">
                                — {{ formatDate(item.resolvido_em) }}
                            </span>
                        </p>
                    </div>
                    <div v-if="item.tags && item.tags.length" class="audit-tags">
                        <span v-for="tag in item.tags" :key="tag" class="tag">#{{ tag }}</span>
                    </div>
                </div>
            </article>
        </div>

        <!-- Drawer de edição -->
        <DevDrawer
            :open="drawerOpen"
            :title="editingId ? 'Editar bug/débito' : 'Novo bug/débito'"
            :subtitle="editingId ? `#${editingId}` : 'Preencha os campos e salve'"
            :can-save="!!form.titulo.trim()"
            :saving="saving"
            :danger="!!editingId"
            @close="drawerOpen = false"
            @save="save"
            @delete="askDelete"
        >
            <DevField label="Título" required>
                <input v-model="form.titulo" placeholder="Ex.: Memory leak no useRecurrence" />
            </DevField>

            <div class="form-row">
                <DevField label="Status">
                    <select v-model="form.status">
                        <option value="aberto">Aberto</option>
                        <option value="em_analise">Em análise</option>
                        <option value="resolvido">Resolvido</option>
                        <option value="wontfix">Won't fix</option>
                        <option value="duplicado">Duplicado</option>
                    </select>
                </DevField>

                <DevField label="Severidade">
                    <select v-model="form.severidade">
                        <option value="">—</option>
                        <option value="critico">Crítico</option>
                        <option value="alto">Alto</option>
                        <option value="medio">Médio</option>
                        <option value="baixo">Baixo</option>
                    </select>
                </DevField>
            </div>

            <DevField label="Categoria" hint="Ex.: Bug crítico, Dívida técnica, Performance, Arquitetura, Segurança">
                <input v-model="form.categoria" placeholder="Categoria" />
            </DevField>

            <DevField label="Descrição do problema" hint="O que tá errado, onde acontece, como reproduzir">
                <textarea v-model="form.descricao_problema" rows="4" />
            </DevField>

            <DevField label="Solução" hint="Como foi/será resolvido">
                <textarea v-model="form.solucao" rows="3" />
            </DevField>

            <div class="form-row">
                <DevField label="Data de resolução">
                    <input v-model="form.resolvido_em" type="date" />
                </DevField>

                <DevField label="Sessão de resolução" hint="Ex.: Sessão 3 — 2026-03-11">
                    <input v-model="form.sessao_resolucao" />
                </DevField>
            </div>

            <DevField label="Arquivo afetado" hint="src/features/agenda/...">
                <input v-model="form.arquivo_afetado" placeholder="Caminho do arquivo" />
            </DevField>

            <DevField label="Tags" hint="Separe por vírgula. Ex.: agenda, recorrência, n+1">
                <input v-model="form.tags" placeholder="tag1, tag2, tag3" />
            </DevField>
        </DevDrawer>
    </div>
</template>

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

.auditoria { 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-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: 200px; }
.filter-sel { min-width: 160px; 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; }

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

.audit-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; }

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

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

.audit-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);
}

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

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

.audit-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;
}
</style>
