<!--
|--------------------------------------------------------------------------
| Agência PSI — Créditos WhatsApp (Marco B)
|--------------------------------------------------------------------------
| Saldo + loja de pacotes + histórico de compras e uso.
| Créditos são consumidos apenas no canal Oficial AgenciaPSI (Twilio);
| WhatsApp Pessoal (Evolution) é gratuito.
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import { useTenantStore } from '@/stores/tenantStore';
import { useWhatsappCredits } from '@/composables/useWhatsappCredits';
import { isValidCPF, fmtCPF, isValidCNPJ, fmtCNPJ } from '@/utils/validators';

const route = useRoute();
const toast = useToast();
const tenantStore = useTenantStore();
const api = useWhatsappCredits();

// Em /melissa o card vive numa coluna mais estreita — limita a loja de
// pacotes a 2 por linha (1 no mobile). /configuracoes mantem 4 por linha.
const inMelissa = computed(() => String(route.path || '').startsWith('/melissa'));
const pkgGridClass = computed(() => (
    inMelissa.value
        ? 'grid grid-cols-1 md:grid-cols-2 gap-3'
        : 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'
));

// Dialog de confirmação (coleta CPF/CNPJ antes de criar a cobrança)
const confirmDlg = reactive({
    open: false,
    pkg: null,
    docInput: '',
    error: ''
});

// Dialog de pagamento PIX
const pixDlg = reactive({
    open: false,
    purchase: null,
});

function formatDoc(digits) {
    const d = String(digits || '').replace(/\D/g, '');
    if (d.length === 11) return fmtCPF(d);
    if (d.length === 14) return fmtCNPJ(d);
    return d;
}

function validateDoc(raw) {
    const d = String(raw || '').replace(/\D/g, '');
    if (!d) return { ok: false, error: 'Informe o CPF ou CNPJ do titular.' };
    if (d.length === 11) {
        if (!isValidCPF(d)) return { ok: false, error: 'CPF inválido. Confira os dígitos.' };
        return { ok: true, digits: d };
    }
    if (d.length === 14) {
        if (!isValidCNPJ(d)) return { ok: false, error: 'CNPJ inválido. Confira os dígitos.' };
        return { ok: true, digits: d };
    }
    return { ok: false, error: 'Informe 11 dígitos (CPF) ou 14 (CNPJ).' };
}

function openConfirm(pkg) {
    confirmDlg.pkg = pkg;
    confirmDlg.docInput = formatDoc(api.tenantCpfCnpj.value);
    confirmDlg.error = '';
    confirmDlg.open = true;
}

async function onConfirmBuy() {
    const v = validateDoc(confirmDlg.docInput);
    if (!v.ok) { confirmDlg.error = v.error; return; }
    confirmDlg.error = '';

    const res = await api.createPurchase(confirmDlg.pkg.id, v.digits);
    if (!res.ok) {
        const msg = res.message
            || (res.error?.includes('não configurado')
                ? 'Sistema de pagamento não está configurado. Contate o suporte.'
                : res.error || 'Falha ao criar cobrança');
        toast.add({ severity: 'error', summary: 'Erro', detail: msg, life: 5000 });
        return;
    }
    confirmDlg.open = false;
    pixDlg.purchase = res.purchase;
    pixDlg.open = true;
}

function copyPix() {
    const code = pixDlg.purchase?.asaas_pix_copy_paste;
    if (!code) return;
    navigator.clipboard.writeText(code).then(
        () => toast.add({ severity: 'success', summary: 'Código copiado', life: 1800 }),
        () => toast.add({ severity: 'error', summary: 'Falha ao copiar', life: 2500 })
    );
}

// Threshold edit
const editingThreshold = ref(false);
const thresholdInput = ref(20);

function startEditThreshold() {
    thresholdInput.value = api.balance.value?.low_balance_threshold ?? 20;
    editingThreshold.value = true;
}

async function saveThreshold() {
    const res = await api.updateLowBalanceThreshold(thresholdInput.value);
    if (res.ok) {
        toast.add({ severity: 'success', summary: 'Alerta atualizado', life: 2000 });
        editingThreshold.value = false;
    } else {
        toast.add({ severity: 'error', summary: 'Erro', detail: res.error, life: 3500 });
    }
}

// Formatters
function brl(v) {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(Number(v) || 0);
}
function fmtDate(iso) {
    if (!iso) return '';
    return new Date(iso).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}

const kindLabel = {
    purchase: { label: 'Compra', icon: 'pi pi-shopping-cart', cls: 'text-green-500' },
    topup_manual: { label: 'Topup manual', icon: 'pi pi-plus-circle', cls: 'text-sky-500' },
    usage: { label: 'Uso', icon: 'pi pi-send', cls: 'text-orange-500' },
    refund: { label: 'Estorno', icon: 'pi pi-replay', cls: 'text-amber-500' },
    adjustment: { label: 'Ajuste', icon: 'pi pi-pencil', cls: 'text-slate-500' }
};

const statusLabel = {
    pending: { label: 'Aguardando pagamento', cls: 'bg-amber-500/10 text-amber-600' },
    paid: { label: 'Pago', cls: 'bg-green-500/10 text-green-600' },
    failed: { label: 'Falhou', cls: 'bg-red-500/10 text-red-600' },
    expired: { label: 'Expirado', cls: 'bg-slate-500/10 text-slate-600' },
    cancelled: { label: 'Cancelado', cls: 'bg-slate-500/10 text-slate-600' },
    refunded: { label: 'Estornado', cls: 'bg-orange-500/10 text-orange-600' }
};

const pendingPurchases = computed(() => api.purchases.value.filter((p) => p.status === 'pending'));

function reopenPixDialog(purchase) {
    pixDlg.purchase = purchase;
    pixDlg.open = true;
}

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

<template>
    <Teleport to="#cfg-page-actions" defer>
        <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.loadAll()"
        />
    </Teleport>

    <div class="flex flex-col gap-4">
        <!-- Saldo atual -->
        <div
            class="rounded-md border p-4 flex items-center gap-4 flex-wrap"
            :class="api.isLow.value && api.currentBalance.value > 0
                ? 'border-amber-500/30 bg-amber-500/5'
                : api.currentBalance.value === 0
                    ? 'border-red-500/30 bg-red-500/5'
                    : 'border-emerald-500/25 bg-emerald-500/5'"
        >
            <div class="grid place-items-center w-14 h-14 rounded-md shrink-0" :class="api.currentBalance.value === 0 ? 'bg-red-500/10 text-red-500' : api.isLow.value ? 'bg-amber-500/10 text-amber-500' : 'bg-emerald-500/10 text-emerald-500'">
                <i class="pi pi-credit-card text-2xl" />
            </div>
            <div class="flex-1 min-w-0">
                <div class="text-xs uppercase tracking-wider font-semibold text-[var(--text-color-secondary)]">Saldo atual</div>
                <div class="text-3xl font-bold leading-tight">
                    <template v-if="api.loading.value && !api.balance.value">
                        <Skeleton width="8rem" height="2rem" />
                    </template>
                    <template v-else>
                        {{ api.currentBalance.value }} <span class="text-base font-normal text-[var(--text-color-secondary)]">créditos</span>
                    </template>
                </div>
                <div class="text-xs text-[var(--text-color-secondary)] mt-1">
                    <span v-if="api.balance.value">
                        Comprados: <strong>{{ api.balance.value.lifetime_purchased || 0 }}</strong>
                        · Usados: <strong>{{ api.balance.value.lifetime_used || 0 }}</strong>
                    </span>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <template v-if="!editingThreshold">
                    <span class="text-xs text-[var(--text-color-secondary)]">
                        Alerta abaixo de <strong>{{ api.balance.value?.low_balance_threshold ?? 20 }}</strong>
                    </span>
                    <Button icon="pi pi-pencil" severity="secondary" text size="small" class="h-7 w-7" v-tooltip.top="'Editar'" @click="startEditThreshold" />
                </template>
                <template v-else>
                    <InputNumber v-model="thresholdInput" :min="0" :max="10000" inputClass="!w-20 text-xs" />
                    <Button icon="pi pi-check" size="small" severity="primary" class="h-7 w-7" @click="saveThreshold" />
                    <Button icon="pi pi-times" severity="secondary" text size="small" class="h-7 w-7" @click="editingThreshold = false" />
                </template>
            </div>
        </div>

        <!-- Info: só Oficial consome -->
        <div class="rounded-md border border-sky-500/25 bg-sky-500/5 p-3 flex items-start gap-2 text-xs text-[var(--text-color)]">
            <i class="pi pi-info-circle text-sky-500 mt-0.5" />
            <div>
                Créditos são consumidos apenas no canal <strong>WhatsApp Oficial AgenciaPSI</strong>. O <strong>WhatsApp Pessoal</strong> (via QR code) é gratuito mas tem limitações (celular precisa estar ligado, sem SLA, risco de ban).
                <br/>
                <strong>1 crédito = 1 mensagem enviada.</strong> Mensagens recebidas não consomem. Saldo não expira.
            </div>
        </div>

        <!-- Ordens pendentes (CTA pra pagar) -->
        <div v-if="pendingPurchases.length" class="rounded-md border border-amber-500/30 bg-amber-500/5 p-4">
            <div class="flex items-center gap-2 mb-2">
                <i class="pi pi-clock text-amber-500" />
                <span class="text-sm font-bold">{{ pendingPurchases.length }} cobrança{{ pendingPurchases.length > 1 ? 's' : '' }} aguardando pagamento</span>
            </div>
            <div class="flex flex-col gap-1.5">
                <div v-for="p in pendingPurchases" :key="p.id" class="flex items-center justify-between gap-2 p-2 rounded bg-[var(--surface-card)] text-sm">
                    <span class="truncate">{{ p.package_name }} — {{ p.credits }} créditos · {{ brl(p.amount_brl) }}</span>
                    <Button label="Pagar" icon="pi pi-qrcode" size="small" class="rounded-full" @click="reopenPixDialog(p)" />
                </div>
            </div>
        </div>

        <!-- Loja de pacotes -->
        <div class="flex flex-col gap-3">
            <div class="flex items-center gap-2">
                <i class="pi pi-shopping-cart text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Comprar créditos</span>
            </div>

            <div v-if="api.loading.value && !api.packages.value.length" :class="pkgGridClass">
                <Skeleton v-for="n in 4" :key="n" height="12rem" class="rounded-md" />
            </div>

            <div v-else-if="!api.packages.value.length" class="text-center py-8 text-sm text-[var(--text-color-secondary)] italic">
                Nenhum pacote disponível no momento. Contate o suporte.
            </div>

            <div v-else :class="pkgGridClass">
                <div
                    v-for="pkg in api.packages.value"
                    :key="pkg.id"
                    class="relative flex flex-col gap-3 p-4 rounded-md border-2 bg-[var(--surface-card)] transition-all hover:shadow-md"
                    :class="pkg.is_featured ? 'border-emerald-500 shadow-[0_0_0_3px_rgba(34,197,94,0.1)]' : 'border-[var(--surface-border)] hover:border-indigo-300'"
                >
                    <span v-if="pkg.is_featured" class="absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-full text-[0.6rem] font-bold uppercase tracking-wide bg-emerald-500 text-white">
                        ⭐ Mais vendido
                    </span>
                    <div class="text-sm font-bold text-[var(--text-color)]">{{ pkg.name }}</div>
                    <div v-if="pkg.description" class="text-xs text-[var(--text-color-secondary)]">{{ pkg.description }}</div>

                    <div class="flex flex-col gap-0.5">
                        <div class="text-[1.6rem] font-bold leading-none text-[var(--primary-color)]">{{ pkg.credits }}</div>
                        <div class="text-xs text-[var(--text-color-secondary)]">mensagens</div>
                    </div>

                    <div class="flex flex-col gap-0.5 mt-auto">
                        <div class="text-2xl font-bold">{{ brl(pkg.price_brl) }}</div>
                        <div class="text-[0.7rem] text-[var(--text-color-secondary)]">{{ brl(pkg.price_brl / pkg.credits) }} / mensagem</div>
                    </div>

                    <Button
                        label="Comprar"
                        icon="pi pi-shopping-cart"
                        :severity="pkg.is_featured ? 'primary' : 'secondary'"
                        :outlined="!pkg.is_featured"
                        class="rounded-full"
                        :loading="api.creating.value"
                        @click="openConfirm(pkg)"
                    />
                </div>
            </div>
        </div>

        <!-- Histórico de compras -->
        <div v-if="api.purchases.value.length" class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-2">
            <div class="flex items-center gap-2 mb-1">
                <i class="pi pi-receipt text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Histórico de compras</span>
            </div>
            <div class="flex flex-col gap-1.5 max-h-[360px] overflow-y-auto">
                <div
                    v-for="p in api.purchases.value"
                    :key="p.id"
                    class="flex items-center gap-2 p-2 rounded-md border border-[var(--surface-border)] text-sm"
                >
                    <span class="inline-flex items-center px-1.5 py-px rounded text-[0.65rem] font-bold uppercase shrink-0" :class="statusLabel[p.status]?.cls">
                        {{ statusLabel[p.status]?.label || p.status }}
                    </span>
                    <span class="flex-1 truncate">{{ p.package_name }} — {{ p.credits }} créditos</span>
                    <span class="font-semibold">{{ brl(p.amount_brl) }}</span>
                    <span class="text-xs text-[var(--text-color-secondary)] shrink-0">{{ fmtDate(p.paid_at || p.created_at) }}</span>
                </div>
            </div>
        </div>

        <!-- Extrato -->
        <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-card)] p-4 flex flex-col gap-2">
            <div class="flex items-center gap-2 mb-1">
                <i class="pi pi-list text-[var(--primary-color)]" />
                <span class="text-sm font-bold uppercase tracking-wide">Extrato (50 últimos)</span>
            </div>
            <div v-if="!api.transactions.value.length" class="text-xs text-[var(--text-color-secondary)] italic text-center py-4">
                Nenhuma transação ainda.
            </div>
            <div v-else class="flex flex-col gap-0.5 max-h-[300px] overflow-y-auto text-xs">
                <div
                    v-for="tx in api.transactions.value"
                    :key="tx.id"
                    class="grid grid-cols-[auto_1fr_auto_auto] items-center gap-2 py-1.5 px-2 rounded hover:bg-[var(--surface-hover)]"
                >
                    <i :class="[kindLabel[tx.kind]?.icon || 'pi pi-circle', kindLabel[tx.kind]?.cls || '']" />
                    <span>{{ kindLabel[tx.kind]?.label || tx.kind }}<span v-if="tx.note" class="ml-1 text-[var(--text-color-secondary)]">— {{ tx.note }}</span></span>
                    <span class="font-bold font-mono" :class="tx.amount > 0 ? 'text-green-600' : 'text-orange-600'">
                        {{ tx.amount > 0 ? '+' : '' }}{{ tx.amount }}
                    </span>
                    <span class="text-[var(--text-color-secondary)]">{{ fmtDate(tx.created_at) }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Dialog de confirmação (CPF/CNPJ + resumo) -->
    <Dialog
        v-model:visible="confirmDlg.open"
        :header="`Comprar ${confirmDlg.pkg?.name || 'pacote'}`"
        modal
        :style="{ width: 'min(440px, 95vw)' }"
        @hide="confirmDlg.error = ''"
    >
        <div v-if="confirmDlg.pkg" class="flex flex-col gap-3">
            <div class="rounded-md border border-[var(--surface-border)] bg-[var(--surface-ground)] p-3 flex items-center justify-between">
                <div class="flex flex-col">
                    <span class="text-xs uppercase tracking-wide text-[var(--text-color-secondary)] font-semibold">{{ confirmDlg.pkg.name }}</span>
                    <span class="text-sm">{{ confirmDlg.pkg.credits }} créditos (mensagens WhatsApp)</span>
                </div>
                <span class="text-xl font-bold text-[var(--primary-color)]">{{ brl(confirmDlg.pkg.price_brl) }}</span>
            </div>

            <div class="flex flex-col gap-1">
                <label class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">
                    CPF ou CNPJ do titular <span class="text-red-500">*</span>
                </label>
                <InputText
                    v-model="confirmDlg.docInput"
                    placeholder="000.000.000-00"
                    :invalid="!!confirmDlg.error"
                    @input="confirmDlg.error = ''"
                    @blur="confirmDlg.docInput = formatDoc(confirmDlg.docInput)"
                    @keydown.enter="onConfirmBuy"
                    maxlength="20"
                />
                <small v-if="confirmDlg.error" class="text-red-500">{{ confirmDlg.error }}</small>
                <small v-else class="text-[var(--text-color-secondary)]">
                    Exigido pelo gateway (Asaas). Fica salvo no seu tenant pras próximas compras.
                </small>
            </div>

            <div class="rounded-md bg-[var(--surface-ground)] p-2 text-xs text-[var(--text-color-secondary)]">
                <i class="pi pi-info-circle mr-1 text-sky-500" />
                Ao confirmar, geramos um QR Code PIX. Os créditos aparecem automaticamente após o pagamento (poucos segundos).
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" text @click="confirmDlg.open = false" />
            <Button
                label="Gerar cobrança PIX"
                icon="pi pi-qrcode"
                :loading="api.creating.value"
                @click="onConfirmBuy"
            />
        </template>
    </Dialog>

    <!-- Dialog PIX -->
    <Dialog
        v-model:visible="pixDlg.open"
        header="Pagamento PIX"
        modal
        :style="{ width: 'min(420px, 95vw)' }"
    >
        <div v-if="pixDlg.purchase" class="flex flex-col gap-3">
            <div class="text-center">
                <div class="text-xs uppercase text-[var(--text-color-secondary)] font-semibold tracking-wide mb-1">Valor total</div>
                <div class="text-3xl font-bold text-[var(--primary-color)]">{{ brl(pixDlg.purchase.amount_brl) }}</div>
                <div class="text-sm text-[var(--text-color-secondary)]">{{ pixDlg.purchase.package_name }} · {{ pixDlg.purchase.credits }} créditos</div>
            </div>

            <div v-if="pixDlg.purchase.asaas_pix_qrcode" class="flex flex-col items-center gap-2">
                <img :src="`data:image/png;base64,${pixDlg.purchase.asaas_pix_qrcode}`" alt="QR Code PIX" class="w-48 h-48 rounded-md border border-[var(--surface-border)]" />
                <span class="text-xs text-[var(--text-color-secondary)]">Aponte a câmera do banco pro QR Code</span>
            </div>

            <div v-if="pixDlg.purchase.asaas_pix_copy_paste" class="flex flex-col gap-1">
                <span class="text-xs font-semibold uppercase tracking-wide text-[var(--text-color-secondary)]">Ou copie o código PIX</span>
                <div class="flex gap-1">
                    <InputText :modelValue="pixDlg.purchase.asaas_pix_copy_paste" readonly class="flex-1 text-xs font-mono" />
                    <Button icon="pi pi-copy" severity="secondary" outlined v-tooltip.top="'Copiar'" @click="copyPix" />
                </div>
            </div>

            <div v-if="pixDlg.purchase.asaas_payment_link" class="text-center">
                <a :href="pixDlg.purchase.asaas_payment_link" target="_blank" rel="noopener" class="text-xs text-[var(--primary-color)] underline">
                    Ou pague com cartão (link externo)
                </a>
            </div>

            <div class="rounded-md bg-[var(--surface-ground)] p-2 text-xs text-[var(--text-color-secondary)]">
                <i class="pi pi-info-circle mr-1 text-sky-500" />
                Assim que o pagamento for confirmado (PIX é instantâneo), seu saldo é atualizado automaticamente. Pode fechar essa janela — a confirmação aparece aqui quando concluída.
            </div>
        </div>

        <template #footer>
            <Button label="Fechar" severity="secondary" text @click="pixDlg.open = false" />
            <Button label="Já paguei, atualizar" icon="pi pi-refresh" @click="api.loadAll(); pixDlg.open = false;" />
        </template>
    </Dialog>
</template>
