<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/views/pages/saas/SaasPlansPage.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { supabase } from '@/lib/supabase/client';

import InputNumber from 'primevue/inputnumber';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';

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

const loading = ref(false);
const rows = ref([]);

const showDlg = ref(false);
const saving = ref(false);
const isEdit = ref(false);

const CORE_PLAN_KEYS = new Set(['clinic_free', 'clinic_pro', 'therapist_free', 'therapist_pro']);

const targetOptions = [
    { label: 'Clínica', value: 'clinic' },
    { label: 'Terapeuta', value: 'therapist' },
    { label: 'Supervisor', value: 'supervisor' }
];

const targetFilter = ref('all'); // 'all' | 'clinic' | 'therapist' | 'supervisor'
const targetFilterOptions = [
    { label: 'Todos', value: 'all' },
    { label: 'Clínica', value: 'clinic' },
    { label: 'Terapeuta', value: 'therapist' },
    { label: 'Supervisor', value: 'supervisor' }
];

const filteredRows = computed(() => {
    const t = targetFilter.value;
    if (t === 'all') return rows.value;
    return (rows.value || []).filter((r) => r.target === t);
});

const form = ref({
    id: null,
    key: '',
    name: '',
    target: 'clinic', // 'clinic' | 'therapist' | 'supervisor'
    price_monthly: null,
    price_yearly: null,
    max_supervisees: null // apenas para target=supervisor
});

const hasCreatedAt = computed(() => rows.value?.length && 'created_at' in rows.value[0]);

const normalizedKey = computed(() =>
    String(form.value.key || '')
        .trim()
        .toLowerCase()
);
const isCorePlanEditing = computed(() => isEdit.value && CORE_PLAN_KEYS.has(normalizedKey.value));
const isTargetLocked = computed(() => isEdit.value); // 🔒 plano existente não troca target
const isDeleteLockedRow = (row) =>
    CORE_PLAN_KEYS.has(
        String(row?.key || '')
            .trim()
            .toLowerCase()
    );

function isUniqueViolation(err) {
    if (!err) return false;
    if (err.code === '23505') return true;
    const msg = String(err.message || '');
    return msg.includes('duplicate key value') || msg.includes('unique constraint');
}

function isFkViolation(err) {
    if (!err) return false;
    if (err.code === '23503') return true;
    const msg = String(err.message || '').toLowerCase();
    return msg.includes('foreign key') || msg.includes('violates foreign key');
}

// slug técnico para key (sem acento, sem espaço, lowercase, só [a-z0-9_])
function slugifyKey(s) {
    return String(s || '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .trim()
        .replace(/\s+/g, '_')
        .replace(/[^a-z0-9_]/g, '');
}

function formatBRLFromCents(cents) {
    if (cents == null) return '—';
    const v = Number(cents) / 100;
    return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function toCents(valueReais) {
    if (valueReais == null || valueReais === '') return null;
    const n = Number(valueReais);
    if (Number.isNaN(n)) return null;
    return Math.round(n * 100);
}

function fromCentsToReais(cents) {
    if (cents == null) return null;
    return Number(cents) / 100;
}

function formatTargetLabel(t) {
    if (t === 'clinic') return 'Clínica';
    if (t === 'therapist') return 'Terapeuta';
    if (t === 'supervisor') return 'Supervisor';
    return t || '—';
}

async function fetchAll() {
    loading.value = true;
    try {
        // 1) planos
        const { data: p, error: ep } = await supabase.from('plans').select('*').order('key', { ascending: true });
        if (ep) throw ep;

        // 2) preços ativos (view)
        const { data: ap, error: eap } = await supabase.from('v_plan_active_prices').select('*');
        if (eap) throw eap;

        const priceMap = new Map();
        for (const r of ap || []) priceMap.set(r.plan_id, r);

        rows.value = (p || []).map((plan) => {
            const pr = priceMap.get(plan.id) || {};
            return {
                ...plan,
                monthly_cents: pr.monthly_cents ?? null,
                yearly_cents: pr.yearly_cents ?? null
            };
        });
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro', detail: e.message || String(e), life: 4500 });
    } finally {
        loading.value = false;
    }
}

function openEdit(row) {
    isEdit.value = true;
    form.value = {
        id: row.id,
        key: row.key ?? '',
        name: row.name ?? '',
        target: row.target || 'clinic',
        price_monthly: fromCentsToReais(row.monthly_cents),
        price_yearly: fromCentsToReais(row.yearly_cents),
        max_supervisees: row.max_supervisees ?? null
    };
    showDlg.value = true;
}

function openCreate() {
    isEdit.value = false;
    const suggestedTarget = targetFilter.value !== 'all' ? targetFilter.value : 'clinic';

    form.value = {
        id: null,
        key: '',
        name: '',
        target: suggestedTarget,
        price_monthly: null,
        price_yearly: null,
        max_supervisees: null
    };

    showDlg.value = true;
}

function validate() {
    const k = slugifyKey(form.value.key);

    if (!k) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe a key do plano.', life: 3000 });
        return false;
    }

    const n = String(form.value.name || '').trim();
    if (!n) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Informe o nome do plano.', life: 3000 });
        return false;
    }

    if (!form.value.target || !['clinic', 'therapist', 'supervisor'].includes(form.value.target)) {
        toast.add({ severity: 'warn', summary: 'Atenção', detail: 'Selecione o público do plano (Clínica, Terapeuta ou Supervisor).', life: 3000 });
        return false;
    }

    // evita key duplicada no frontend (case-insensitive)
    const exists = rows.value.some(
        (r) =>
            String(r.key || '')
                .trim()
                .toLowerCase() === k && r.id !== form.value.id
    );
    if (exists) {
        toast.add({
            severity: 'warn',
            summary: 'Key já existente',
            detail: 'Já existe um plano com essa key. Use outra.',
            life: 3000
        });
        return false;
    }

    form.value.key = k;
    form.value.name = n;
    return true;
}

async function upsertPlanPrice({ planId, interval, nextCents, prevCents }) {
    const same = (prevCents == null && nextCents == null) || Number(prevCents) === Number(nextCents);

    if (same) return;

    const nowIso = new Date().toISOString();

    // se admin apagou o preço: desativa o ativo
    if (nextCents == null) {
        const { error } = await supabase.from('plan_prices').update({ is_active: false, active_to: nowIso }).eq('plan_id', planId).eq('interval', interval).eq('is_active', true);

        if (error) throw error;
        return;
    }

    // fecha ativo atual (se existir)
    const { error: eClose } = await supabase.from('plan_prices').update({ is_active: false, active_to: nowIso }).eq('plan_id', planId).eq('interval', interval).eq('is_active', true);

    if (eClose) throw eClose;

    // cria novo preço ativo
    const { error: eIns } = await supabase.from('plan_prices').insert({
        plan_id: planId,
        interval,
        amount_cents: nextCents,
        currency: 'BRL',
        is_active: true,
        active_from: nowIso,
        source: 'manual'
    });

    if (eIns) throw eIns;
}

async function save() {
    if (saving.value) return;
    if (!validate()) return;

    saving.value = true;

    try {
        let planId = form.value.id;

        const payload = {
            key: form.value.key,
            name: form.value.name,
            target: form.value.target,
            max_supervisees: form.value.target === 'supervisor' ? (form.value.max_supervisees ?? null) : null
        };

        if (isEdit.value) {
            // 🔒 target não muda em plano existente (UI já bloqueia; DB trigger garante)
            const { error } = await supabase.from('plans').update(payload).eq('id', form.value.id);

            if (error) throw error;
        } else {
            const { data, error } = await supabase.from('plans').insert(payload).select('id').single();

            if (error) throw error;
            planId = data.id;
        }

        // preços atuais (da listagem)
        const currentRow = rows.value.find((r) => r.id === planId);
        const prevMonthly = currentRow?.monthly_cents ?? null;
        const prevYearly = currentRow?.yearly_cents ?? null;

        const nextMonthly = toCents(form.value.price_monthly);
        const nextYearly = toCents(form.value.price_yearly);

        await upsertPlanPrice({ planId, interval: 'month', nextCents: nextMonthly, prevCents: prevMonthly });
        await upsertPlanPrice({ planId, interval: 'year', nextCents: nextYearly, prevCents: prevYearly });

        toast.add({
            severity: 'success',
            summary: 'Ok',
            detail: isEdit.value ? 'Plano atualizado.' : 'Plano criado.',
            life: 2500
        });

        showDlg.value = false;
        await fetchAll();
    } catch (e) {
        if (isUniqueViolation(e)) {
            toast.add({
                severity: 'warn',
                summary: 'Key já existente',
                detail: 'Já existe um plano com essa key. Use outra.',
                life: 3500
            });
        } else {
            toast.add({
                severity: 'error',
                summary: 'Erro',
                detail: e.message || String(e),
                life: 4500
            });
        }
    } finally {
        saving.value = false;
    }
}

function askDelete(row) {
    if (isDeleteLockedRow(row)) {
        toast.add({
            severity: 'warn',
            summary: 'Ação não permitida',
            detail: 'Este é um plano padrão do sistema e não pode ser removido.',
            life: 4200
        });
        return;
    }

    confirm.require({
        message: `Excluir o plano "${row.key}"?`,
        header: 'Confirmar exclusão',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        accept: () => doDelete(row)
    });
}

async function doDelete(row) {
    try {
        // V#36: RPC delete_plan_safe valida subscriptions ativas atomicamente
        // (desativa prices + deleta plan no mesmo batch). Bloqueia se houver
        // subscriptions ativas para impedir órfãos.
        const { error } = await supabase.rpc('delete_plan_safe', { p_plan_id: row.id });
        if (error) throw error;

        toast.add({ severity: 'success', summary: 'Ok', detail: 'Plano excluído.', life: 2500 });
        await fetchAll();
    } catch (e) {
        const msg = e?.message || String(e);
        const isBusy = msg.toLowerCase().includes('assinatura') && msg.toLowerCase().includes('ativa');
        const hint = isFkViolation(e) ? 'Esse plano ainda está referenciado (ex.: plan_features ou pricing). Remova vínculos antes de excluir.' : '';

        toast.add({
            severity: isBusy ? 'warn' : 'error',
            summary: isBusy ? 'Plano em uso' : 'Erro',
            detail: hint ? `${msg} — ${hint}` : msg,
            life: 6000
        });
    }
}

// ── Hero sticky ───────────────────────────────────────────
const heroEl = ref(null);
const heroSentinelRef = ref(null);
const heroMenuRef = ref(null);
const heroStuck = ref(false);
let disconnectStickyObserver = null;

const heroMenuItems = computed(() => [
    { label: 'Atualizar', icon: 'pi pi-refresh', command: fetchAll, disabled: loading.value },
    { label: 'Adicionar plano', icon: 'pi pi-plus', command: openCreate },
    { separator: true },
    {
        label: 'Filtrar',
        items: targetFilterOptions.map((o) => ({
            label: o.label,
            command: () => {
                targetFilter.value = o.value;
            }
        }))
    }
]);

onMounted(async () => {
    await fetchAll();

    const sentinel = heroSentinelRef.value;
    if (sentinel) {
        const io = new IntersectionObserver(
            ([entry]) => {
                heroStuck.value = !entry.isIntersecting;
            },
            { rootMargin: `${document.querySelector('.l2-main') ? '0px' : '-56px'} 0px 0px 0px` }
        );
        io.observe(sentinel);
        disconnectStickyObserver = () => io.disconnect();
    }
});

onBeforeUnmount(() => {
    try {
        disconnectStickyObserver?.();
    } catch {}
});
</script>

<template>
    <ConfirmDialog />

    <div class="flex flex-col gap-4 p-4">
        <!-- Header -->
        <div class="cfg-subheader">
            <div class="cfg-subheader__icon"><i class="pi pi-tag" /></div>
            <div class="min-w-0 flex-1">
                <div class="cfg-subheader__title">Planos e preços</div>
                <div class="cfg-subheader__sub">Catálogo de planos do SaaS.</div>
            </div>
            <div class="hidden xl:flex items-center gap-2 shrink-0">
                <SelectButton v-model="targetFilter" :options="targetFilterOptions" optionLabel="label" optionValue="value" size="small" />
                <Button label="Atualizar" icon="pi pi-refresh" severity="secondary" outlined size="small" :loading="loading" :disabled="saving" @click="fetchAll" />
                <Button label="Adicionar plano" icon="pi pi-plus" size="small" :disabled="saving" @click="openCreate" />
            </div>
            <div class="flex xl:hidden shrink-0">
                <Button label="Ações" icon="pi pi-ellipsis-v" severity="warn" size="small" aria-haspopup="true" aria-controls="plans_hero_menu" @click="(e) => heroMenuRef.toggle(e)" />
                <Menu ref="heroMenuRef" id="plans_hero_menu" :model="heroMenuItems" :popup="true" />
            </div>
        </div>
        <DataTable :value="filteredRows" dataKey="id" :loading="loading" stripedRows responsiveLayout="scroll">
            <Column field="name" header="Nome" sortable style="min-width: 14rem" />
            <Column field="key" header="Key" sortable />

            <Column field="target" header="Público" sortable style="width: 10rem">
                <template #body="{ data }">
                    <span class="font-medium">{{ formatTargetLabel(data.target) }}</span>
                </template>
            </Column>

            <Column header="Mensal" sortable style="width: 12rem">
                <template #body="{ data }">
                    <span class="font-medium">{{ formatBRLFromCents(data.monthly_cents) }}</span>
                </template>
            </Column>

            <Column header="Anual" sortable style="width: 12rem">
                <template #body="{ data }">
                    <span class="font-medium">{{ formatBRLFromCents(data.yearly_cents) }}</span>
                </template>
            </Column>

            <Column v-if="hasCreatedAt" field="created_at" header="Criado em" sortable />

            <Column header="Ações" style="width: 12rem">
                <template #body="{ data }">
                    <div class="flex gap-2">
                        <Button icon="pi pi-pencil" severity="secondary" outlined @click="openEdit(data)" />
                        <Button icon="pi pi-trash" severity="danger" outlined :disabled="isDeleteLockedRow(data)" :title="isDeleteLockedRow(data) ? 'Plano padrão do sistema não pode ser removido.' : 'Excluir plano'" @click="askDelete(data)" />
                    </div>
                </template>
            </Column>
        </DataTable>
    </div>

    <Dialog v-model:visible="showDlg" modal :draggable="false" :header="isEdit ? 'Editar plano' : 'Novo plano'" :style="{ width: '620px' }">
        <div class="flex flex-col gap-4">
            <div>
                <label class="block mb-2">Público do plano</label>
                <SelectButton v-model="form.target" :options="targetOptions" optionLabel="label" optionValue="value" class="w-full" :disabled="isTargetLocked || saving" />
                <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">Planos já existentes não mudam de público. Isso evita inconsistência no catálogo.</div>
            </div>

            <FloatLabel variant="on" class="w-full">
                <IconField class="w-full">
                    <InputIcon class="pi pi-tag" />
                    <InputText v-model="form.key" id="plan_key" class="w-full pr-10" variant="filled" placeholder="ex.: clinic_pro" :disabled="isCorePlanEditing || saving" @blur="form.key = slugifyKey(form.key)" />
                </IconField>
                <label for="plan_key">Key</label>
            </FloatLabel>
            <div class="text-[1rem] text-[var(--text-color-secondary)] -mt-3">Key é técnica e estável (slug). Planos padrão do sistema têm a key protegida.</div>

            <FloatLabel variant="on" class="w-full">
                <IconField class="w-full">
                    <InputIcon class="pi pi-bookmark" />
                    <InputText v-model="form.name" id="plan_name" class="w-full pr-10" variant="filled" placeholder="ex.: Clínica PRO" :disabled="saving" />
                </IconField>
                <label for="plan_name">Nome</label>
            </FloatLabel>
            <div class="text-[1rem] text-[var(--text-color-secondary)] -mt-3">Nome interno para administração. (Nome público vem de <b>plan_public</b>.)</div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <FloatLabel variant="on" class="w-full">
                        <IconField class="w-full">
                            <InputIcon class="pi pi-money-bill" />
                            <InputNumber
                                v-model="form.price_monthly"
                                inputId="price_monthly"
                                class="w-full"
                                inputClass="w-full pr-10"
                                variant="filled"
                                mode="decimal"
                                :minFractionDigits="2"
                                :maxFractionDigits="2"
                                placeholder="ex.: 49,90"
                                :disabled="saving"
                            />
                        </IconField>
                        <label for="price_monthly">Preço mensal (R$)</label>
                    </FloatLabel>
                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">Deixe vazio para "sem preço definido".</div>
                </div>

                <div>
                    <FloatLabel variant="on" class="w-full">
                        <IconField class="w-full">
                            <InputIcon class="pi pi-calendar" />
                            <InputNumber
                                v-model="form.price_yearly"
                                inputId="price_yearly"
                                class="w-full"
                                inputClass="w-full pr-10"
                                variant="filled"
                                mode="decimal"
                                :minFractionDigits="2"
                                :maxFractionDigits="2"
                                placeholder="ex.: 490,00"
                                :disabled="saving"
                            />
                        </IconField>
                        <label for="price_yearly">Preço anual (R$)</label>
                    </FloatLabel>
                    <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">Deixe vazio para "sem preço definido".</div>
                </div>
            </div>

            <!-- max_supervisees: só para planos de supervisor -->
            <div v-if="form.target === 'supervisor'">
                <FloatLabel variant="on" class="w-full">
                    <IconField class="w-full">
                        <InputIcon class="pi pi-users" />
                        <InputNumber v-model="form.max_supervisees" inputId="max_supervisees" class="w-full" inputClass="w-full pr-10" variant="filled" :useGrouping="false" :min="1" placeholder="ex.: 3" :disabled="saving" />
                    </IconField>
                    <label for="max_supervisees">Limite de supervisionados</label>
                </FloatLabel>
                <div class="text-[1rem] text-[var(--text-color-secondary)] mt-1">Número máximo de terapeutas que podem ser supervisionados neste plano.</div>
            </div>
        </div>

        <template #footer>
            <Button label="Cancelar" severity="secondary" outlined @click="showDlg = false" :disabled="saving" />
            <Button :label="isEdit ? 'Salvar' : 'Criar'" icon="pi pi-check" :loading="saving" @click="save" />
        </template>
    </Dialog>
</template>