<!--
|--------------------------------------------------------------------------
| Agência PSI — Portal do Paciente · Documentos para assinatura
|--------------------------------------------------------------------------
| Lista as solicitações de assinatura do paciente logado:
|   - pendente/enviado  → botão "Assinar agora" → /shared/document/:token
|   - assinado          → mostra data + hash + IP (audit)
|   - recusado          → mostra data + motivo (se houver)
|--------------------------------------------------------------------------
-->
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useDocumentSignatures } from '@/features/documents/composables/useDocumentSignatures';

const router = useRouter();
const { signatures, loading, error, loadMine } = useDocumentSignatures();

const statusFilter = ref('todos'); // todos | pendentes | assinados

const filtered = computed(() => {
    const all = signatures.value || [];
    if (statusFilter.value === 'pendentes') {
        return all.filter(s => s.status === 'pendente' || s.status === 'enviado');
    }
    if (statusFilter.value === 'assinados') {
        return all.filter(s => s.status === 'assinado');
    }
    return all;
});

const counts = computed(() => {
    const all = signatures.value || [];
    return {
        total: all.length,
        pendentes: all.filter(s => s.status === 'pendente' || s.status === 'enviado').length,
        assinados: all.filter(s => s.status === 'assinado').length,
        recusados: all.filter(s => s.status === 'recusado').length
    };
});

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

function statusBadge(s) {
    const map = {
        pendente:  { label: 'Pendente',  class: 'bg-amber-100 text-amber-700 border-amber-200' },
        enviado:   { label: 'Enviado',   class: 'bg-blue-100 text-blue-700 border-blue-200' },
        assinado:  { label: 'Assinado',  class: 'bg-emerald-100 text-emerald-700 border-emerald-200' },
        recusado:  { label: 'Recusado',  class: 'bg-rose-100 text-rose-700 border-rose-200' },
        expirado:  { label: 'Expirado',  class: 'bg-zinc-100 text-zinc-600 border-zinc-200' }
    };
    return map[s] || { label: s, class: 'bg-zinc-100 text-zinc-600' };
}

function openSignFlow(sig) {
    if (!sig.share_token) {
        // Sem share link válido — terapeuta precisa gerar um. Mostra aviso.
        return;
    }
    router.push({ name: 'shared.document', params: { token: sig.share_token } });
}

onMounted(() => {
    loadMine();
});
</script>

<template>
    <div class="p-4 md:p-6">
        <!-- Header -->
        <div class="mb-6 overflow-hidden rounded-2xl border border-[var(--surface-border)] bg-[var(--surface-card)]">
            <div class="relative p-6">
                <div class="pointer-events-none absolute inset-0 opacity-80">
                    <div class="absolute -top-16 -right-16 h-52 w-52 rounded-full bg-indigo-400/10 blur-3xl" />
                    <div class="absolute bottom-0 left-10 h-44 w-44 rounded-full bg-emerald-400/10 blur-3xl" />
                </div>

                <div class="relative flex items-center gap-4">
                    <div class="grid h-14 w-14 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
                        <i class="pi pi-file-edit text-2xl" />
                    </div>
                    <div class="min-w-0 flex-1">
                        <div class="text-2xl font-semibold leading-none">Documentos para assinatura</div>
                        <div class="mt-2 text-sm text-color-secondary">
                            Termos e documentos solicitados pelo(a) seu(sua) terapeuta. Você pode assinar pelo link enviado ou clicar em "Assinar agora".
                        </div>
                    </div>
                </div>

                <!-- KPIs -->
                <div class="relative mt-6 grid grid-cols-2 gap-3 md:grid-cols-4">
                    <button
                        :class="['rounded-xl border p-3 text-left transition', statusFilter === 'todos' ? 'border-[var(--primary-color)] bg-[var(--primary-color)]/5' : 'border-[var(--surface-border)] hover:border-[var(--primary-color)]/40']"
                        @click="statusFilter = 'todos'"
                    >
                        <div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Total</div>
                        <div class="mt-1 text-xl font-bold">{{ counts.total }}</div>
                    </button>
                    <button
                        :class="['rounded-xl border p-3 text-left transition', statusFilter === 'pendentes' ? 'border-amber-400 bg-amber-50/50' : 'border-[var(--surface-border)] hover:border-amber-300']"
                        @click="statusFilter = 'pendentes'"
                    >
                        <div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Pendentes</div>
                        <div class="mt-1 text-xl font-bold text-amber-700">{{ counts.pendentes }}</div>
                    </button>
                    <button
                        :class="['rounded-xl border p-3 text-left transition', statusFilter === 'assinados' ? 'border-emerald-400 bg-emerald-50/50' : 'border-[var(--surface-border)] hover:border-emerald-300']"
                        @click="statusFilter = 'assinados'"
                    >
                        <div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Assinados</div>
                        <div class="mt-1 text-xl font-bold text-emerald-700">{{ counts.assinados }}</div>
                    </button>
                    <div class="rounded-xl border border-[var(--surface-border)] p-3">
                        <div class="text-[0.7rem] uppercase tracking-wide text-color-secondary">Recusados</div>
                        <div class="mt-1 text-xl font-bold text-rose-700">{{ counts.recusados }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loading -->
        <div v-if="loading && !signatures.length" class="flex flex-col items-center justify-center py-20">
            <i class="pi pi-spinner pi-spin text-3xl text-color-secondary mb-3" />
            <p class="text-sm text-color-secondary">Carregando seus documentos…</p>
        </div>

        <!-- Erro -->
        <div v-else-if="error" class="rounded-xl border border-rose-200 bg-rose-50/50 p-4 text-sm text-rose-700">
            <i class="pi pi-exclamation-triangle mr-2" />{{ error }}
        </div>

        <!-- Empty -->
        <div v-else-if="!filtered.length" class="flex flex-col items-center justify-center rounded-2xl border border-dashed border-[var(--surface-border)] bg-[var(--surface-card)] py-16">
            <div class="mx-auto mb-4 grid h-16 w-16 place-items-center rounded-2xl bg-[var(--primary-color)]/10 text-[var(--primary-color)]">
                <i class="pi pi-inbox text-2xl" />
            </div>
            <div class="text-lg font-semibold">Nenhum documento {{ statusFilter === 'pendentes' ? 'pendente' : statusFilter === 'assinados' ? 'assinado' : '' }} no momento</div>
            <div class="mt-2 text-sm text-color-secondary">Quando seu(sua) terapeuta solicitar assinatura, o documento aparecerá aqui.</div>
        </div>

        <!-- Lista -->
        <div v-else class="space-y-3">
            <div
                v-for="sig in filtered"
                :key="sig.signature_id"
                class="overflow-hidden rounded-xl border border-[var(--surface-border)] bg-[var(--surface-card)] transition hover:border-[var(--primary-color)]/30"
            >
                <div class="flex items-center gap-4 p-4">
                    <!-- Icon -->
                    <div class="grid h-12 w-12 shrink-0 place-items-center rounded-lg bg-blue-50">
                        <i :class="sig.mime_type === 'application/pdf' ? 'pi pi-file-pdf text-red-500' : 'pi pi-file text-blue-500'" class="text-xl" />
                    </div>

                    <!-- Info -->
                    <div class="min-w-0 flex-1">
                        <div class="flex items-center gap-2 flex-wrap">
                            <div class="text-sm font-semibold text-[var(--text-color)] truncate">{{ sig.nome_original || 'Documento sem nome' }}</div>
                            <span :class="['inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[0.65rem] font-medium', statusBadge(sig.status).class]">
                                {{ statusBadge(sig.status).label }}
                            </span>
                        </div>
                        <div class="mt-1 text-xs text-color-secondary">
                            Tipo: <span class="font-medium">{{ sig.tipo_documento || 'outro' }}</span>
                            · Solicitado em {{ fmtDate(sig.criado_em) }}
                            <template v-if="sig.assinado_em">
                                · Assinado em <span class="font-medium text-emerald-700">{{ fmtDate(sig.assinado_em) }}</span>
                            </template>
                        </div>
                    </div>

                    <!-- Ação -->
                    <div class="shrink-0">
                        <button
                            v-if="sig.status === 'pendente' || sig.status === 'enviado'"
                            :disabled="!sig.share_token"
                            :title="!sig.share_token ? 'Link não gerado pelo terapeuta. Solicite que ele(a) compartilhe novamente.' : ''"
                            class="inline-flex items-center gap-2 rounded-lg bg-[var(--primary-color)] px-3 py-2 text-xs font-semibold text-white shadow-sm transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                            @click="openSignFlow(sig)"
                        >
                            <i class="pi pi-pencil" />
                            Assinar agora
                        </button>
                        <div v-else-if="sig.status === 'assinado'" class="text-xs text-emerald-700 font-medium flex items-center gap-1">
                            <i class="pi pi-check-circle" />
                            Concluído
                        </div>
                        <div v-else class="text-xs text-color-secondary">—</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
