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

import { tenantDb } from '@/lib/supabase/tenantClient';
const toast = useToast();

// ── Contexto ──────────────────────────────────────────────────
const userId    = ref(null);
const tenantId  = ref(null);
const loading   = ref(true);

// ── Canal SMS (notification_channels) ─────────────────────────
const channel   = ref(null);
const saving    = ref(false);
const testing   = ref(false);
const testResult = ref(null);  // { success, message, sid? }

const credentials = ref({
    account_sid:  '',
    auth_token:   '',
    from_number:  ''
});

// ── Status ────────────────────────────────────────────────────
const statusInfo = computed(() => {
    if (!channel.value) {
        return { label: 'Não configurado', severity: 'secondary', icon: 'pi pi-minus-circle', color: 'var(--p-gray-400)' };
    }
    switch (channel.value.connection_status) {
        case 'connected':
            return { label: 'Conectado', severity: 'success', icon: 'pi pi-check-circle', color: 'var(--p-green-500)' };
        case 'error':
            return { label: 'Erro na conexão', severity: 'danger', icon: 'pi pi-times-circle', color: 'var(--p-red-500)' };
        default:
            return { label: 'Desconectado', severity: 'secondary', icon: 'pi pi-minus-circle', color: 'var(--p-gray-400)' };
    }
});

const isConfigured = computed(() => !!channel.value);

// ── Logs recentes ─────────────────────────────────────────────
const logs       = ref([]);
const logsLoading = ref(false);

// ── Load ──────────────────────────────────────────────────────
async function init() {
    loading.value = true;
    try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return;
        userId.value  = user.id;

        const { data: profile } = await supabase
            .from('profiles')
            .select('tenant_id')
            .eq('id', user.id)
            .single();

        tenantId.value = profile?.tenant_id || user.id;

        await Promise.all([loadChannel(), loadLogs()]);
    } finally {
        loading.value = false;
    }
}

async function loadChannel() {
    const { data } = await tenantDb().from('notification_channels')
        .select('*')
        .eq('owner_id', userId.value)
        .eq('channel', 'sms')
        .is('deleted_at', null)
        .maybeSingle();

    channel.value = data;

    if (data?.credentials) {
        credentials.value = {
            account_sid:  data.credentials.account_sid  || '',
            auth_token:   data.credentials.auth_token   || '',
            from_number:  data.credentials.from_number  || ''
        };
    }
}

async function loadLogs() {
    logsLoading.value = true;
    const { data } = await tenantDb().from('notification_logs')
        .select('id, template_key, recipient_address, status, failure_reason, provider_message_id, sent_at, failed_at, created_at')
        .eq('owner_id', userId.value)
        .eq('channel', 'sms')
        .order('created_at', { ascending: false })
        .limit(10);

    logsLoading.value = false;
    if (data) logs.value = data;
}

// ── Salvar credenciais ─────────────────────────────────────────
async function saveCredentials() {
    if (saving.value) return;

    if (!credentials.value.account_sid.trim()) {
        toast.add({ severity: 'warn', summary: 'Account SID é obrigatório', life: 3000 });
        return;
    }
    if (!credentials.value.auth_token.trim()) {
        toast.add({ severity: 'warn', summary: 'Auth Token é obrigatório', life: 3000 });
        return;
    }
    if (!credentials.value.from_number.trim()) {
        toast.add({ severity: 'warn', summary: 'Número de origem é obrigatório', life: 3000 });
        return;
    }

    saving.value = true;
    try {
        const creds = { ...credentials.value };

        if (channel.value?.id) {
            const { error } = await tenantDb().from('notification_channels')
                .update({
                    credentials:        creds,
                    is_active:          true,
                    connection_status:  'disconnected'
                })
                .eq('id', channel.value.id);
            if (error) throw error;
        } else {
            const { data, error } = await tenantDb().from('notification_channels')
                .insert({
                    owner_id:           userId.value,
                    channel:            'sms',
                    provider:           'twilio',
                    display_name:       'SMS via Twilio',
                    is_active:          true,
                    connection_status:  'disconnected',
                    credentials:        creds
                })
                .select('*')
                .single();
            if (error) throw error;
            channel.value = data;
        }

        toast.add({ severity: 'success', summary: 'Credenciais salvas', detail: 'Canal SMS configurado com sucesso.', life: 3000 });
        await loadChannel();
    } catch (e) {
        toast.add({ severity: 'error', summary: 'Erro ao salvar', detail: e.message, life: 5000 });
    } finally {
        saving.value = false;
    }
}

// ── Testar conexão ─────────────────────────────────────────────
async function testConnection() {
    if (testing.value) return;
    testing.value  = true;
    testResult.value = null;

    try {
        const { data, error } = await supabase.functions.invoke('test-sms-channel', {
            body: { owner_id: userId.value }
        });

        if (error) throw error;

        testResult.value = data;

        if (data?.success) {
            toast.add({ severity: 'success', summary: 'SMS enviado!', detail: data.message, life: 5000 });

            // Atualiza connection_status para connected
            if (channel.value?.id) {
                await tenantDb().from('notification_channels')
                    .update({ connection_status: 'connected' })
                    .eq('id', channel.value.id);
                channel.value.connection_status = 'connected';
            }

            await loadLogs();
        } else {
            toast.add({ severity: 'warn', summary: 'Falha no teste', detail: data?.message, life: 6000 });

            if (channel.value?.id) {
                await tenantDb().from('notification_channels')
                    .update({ connection_status: 'error' })
                    .eq('id', channel.value.id);
                channel.value.connection_status = 'error';
            }
        }
    } catch (e) {
        testResult.value = { success: false, message: e.message };
        toast.add({ severity: 'error', summary: 'Erro ao testar', detail: e.message, life: 5000 });
    } finally {
        testing.value = false;
    }
}

// ── Helpers ───────────────────────────────────────────────────
function maskPhone(phone) {
    if (!phone || phone.length < 8) return phone || '—';
    return phone.slice(0, 5) + '****' + phone.slice(-4);
}

function logStatusSeverity(status) {
    if (status === 'sent')   return 'success';
    if (status === 'failed') return 'danger';
    return 'secondary';
}

function logStatusLabel(status) {
    const map = { sent: 'Enviado', failed: 'Falhou', pending: 'Pendente', processing: 'Processando' };
    return map[status] || status;
}

function formatDate(iso) {
    if (!iso) return '—';
    return new Date(iso).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' });
}

onMounted(init);
</script>

<template>
    <Toast />

    <div class="flex flex-col gap-5 p-4 md:p-6 max-w-[760px] mx-auto">

        <!-- Loading inicial -->
        <div v-if="loading" class="flex justify-center py-12">
            <ProgressSpinner style="width: 40px; height: 40px" />
        </div>

        <template v-else>

            <!-- ── Status do canal ────────────────────────────────── -->
            <Card>
                <template #content>
                    <div class="flex items-center justify-between gap-4 flex-wrap">
                        <div class="flex items-center gap-4">
                            <div
                                class="grid place-items-center w-12 h-12 rounded-full shrink-0"
                                :style="{ background: `color-mix(in srgb, ${statusInfo.color} 15%, transparent)` }"
                            >
                                <i :class="statusInfo.icon" class="text-xl" :style="{ color: statusInfo.color }" />
                            </div>
                            <div>
                                <div class="font-semibold text-sm mb-1">Canal SMS</div>
                                <Tag :value="statusInfo.label" :severity="statusInfo.severity" />
                            </div>
                        </div>

                        <Button
                            v-if="isConfigured"
                            label="Testar conexão"
                            icon="pi pi-send"
                            size="small"
                            severity="secondary"
                            outlined
                            :loading="testing"
                            @click="testConnection"
                        />
                    </div>

                    <!-- Resultado do teste -->
                    <div v-if="testResult" class="mt-4">
                        <Message
                            :severity="testResult.success ? 'success' : 'error'"
                            :closable="false"
                            class="!mt-0"
                        >
                            <div class="flex flex-col gap-0.5">
                                <span>{{ testResult.message }}</span>
                                <span v-if="testResult.sid" class="text-xs opacity-70 font-mono">SID: {{ testResult.sid }}</span>
                            </div>
                        </Message>
                    </div>

                    <!-- Call-to-action quando não configurado -->
                    <div v-if="!isConfigured" class="mt-4 p-4 rounded-lg border border-dashed border-[var(--surface-border)] bg-[var(--surface-ground)] text-sm text-[var(--text-color-secondary)] text-center">
                        <i class="pi pi-info-circle block text-2xl opacity-40 mb-2" />
                        Canal não configurado. Preencha as credenciais abaixo para ativar o envio de SMS.
                    </div>
                </template>
            </Card>

            <!-- ── Formulário de credenciais ──────────────────────── -->
            <Card>
                <template #title>
                    <div class="flex items-center gap-2 text-base">
                        <i class="pi pi-key opacity-60" />
                        Credenciais Twilio
                    </div>
                </template>
                <template #subtitle>Configure sua conta Twilio para envio de SMS.</template>
                <template #content>
                    <div class="flex flex-col gap-4">

                        <!-- Account SID -->
                        <div class="flex flex-col gap-1.5">
                            <label class="text-xs font-semibold">Account SID</label>
                            <InputText
                                v-model="credentials.account_sid"
                                placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                class="w-full font-mono"
                                autocomplete="off"
                            />
                            <span class="text-xs text-[var(--text-color-secondary)]">Encontre em: Console Twilio → Account Info → Account SID</span>
                        </div>

                        <!-- Auth Token -->
                        <div class="flex flex-col gap-1.5">
                            <label class="text-xs font-semibold">Auth Token</label>
                            <Password
                                v-model="credentials.auth_token"
                                placeholder="••••••••••••••••••••••••••••••••"
                                :feedback="false"
                                toggle-mask
                                class="w-full"
                                input-class="w-full font-mono"
                                autocomplete="new-password"
                            />
                            <span class="text-xs text-[var(--text-color-secondary)]">Encontre em: Console Twilio → Account Info → Auth Token</span>
                        </div>

                        <!-- Número de origem -->
                        <div class="flex flex-col gap-1.5">
                            <label class="text-xs font-semibold">Número de origem</label>
                            <InputText
                                v-model="credentials.from_number"
                                placeholder="+5511999999999"
                                class="w-full font-mono"
                                autocomplete="off"
                            />
                            <span class="text-xs text-[var(--text-color-secondary)]">
                                Use um número Twilio verificado ou o número do seu trial.
                                Formato: +55 (código do país) + DDD + número.
                            </span>
                        </div>

                        <!-- Ações -->
                        <div class="flex items-center justify-between gap-2 pt-1">
                            <Button
                                v-if="isConfigured"
                                label="Testar agora"
                                icon="pi pi-send"
                                size="small"
                                severity="secondary"
                                text
                                :loading="testing"
                                :disabled="saving"
                                @click="testConnection"
                            />
                            <div class="ml-auto">
                                <Button
                                    label="Salvar credenciais"
                                    icon="pi pi-save"
                                    :loading="saving"
                                    :disabled="saving"
                                    @click="saveCredentials"
                                />
                            </div>
                        </div>
                    </div>
                </template>
            </Card>

            <!-- ── Informativo trial/sandbox ──────────────────────── -->
            <Panel toggleable collapsed header="Usando o trial do Twilio?">
                <div class="flex flex-col gap-3 text-sm text-[var(--text-color-secondary)]">
                    <p class="m-0">
                        No plano trial do Twilio, você só pode enviar SMS para números <strong>verificados</strong> na sua conta.
                        Para adicionar um número de teste:
                    </p>
                    <ol class="m-0 pl-5 flex flex-col gap-1">
                        <li>Acesse o Console Twilio</li>
                        <li>Vá em <strong>Phone Numbers → Verified Caller IDs</strong></li>
                        <li>Adicione o número do paciente/teste e siga a verificação por chamada ou SMS</li>
                        <li>Apenas números verificados receberão mensagens no trial</li>
                    </ol>
                    <Message severity="info" :closable="false" class="!mt-1">
                        Quando fizer upgrade para conta paga, essa restrição é removida e qualquer número pode receber SMS.
                    </Message>
                </div>
            </Panel>

            <!-- ── Histórico recente ───────────────────────────────── -->
            <Card>
                <template #title>
                    <div class="flex items-center justify-between">
                        <span class="text-base">Últimos envios</span>
                        <Button icon="pi pi-refresh" text rounded size="small" :loading="logsLoading" @click="loadLogs" />
                    </div>
                </template>
                <template #content>
                    <DataTable
                        :value="logs"
                        :loading="logsLoading"
                        size="small"
                        striped-rows
                        empty-message="Nenhum registro de SMS encontrado."
                    >
                        <Column header="Data" style="width: 130px">
                            <template #body="{ data }">
                                <span class="text-xs">{{ formatDate(data.sent_at || data.failed_at || data.created_at) }}</span>
                            </template>
                        </Column>

                        <Column field="recipient_address" header="Destinatário" style="width: 140px">
                            <template #body="{ data }">
                                <span class="font-mono text-xs">{{ maskPhone(data.recipient_address) }}</span>
                            </template>
                        </Column>

                        <Column field="template_key" header="Template">
                            <template #body="{ data }">
                                <span class="font-mono text-xs text-[var(--text-color-secondary)]">{{ data.template_key }}</span>
                            </template>
                        </Column>

                        <Column header="Status" style="width: 100px">
                            <template #body="{ data }">
                                <Tag
                                    :value="logStatusLabel(data.status)"
                                    :severity="logStatusSeverity(data.status)"
                                    class="text-[0.65rem]"
                                />
                            </template>
                        </Column>

                        <Column header="SID" style="width: 130px">
                            <template #body="{ data }">
                                <span v-if="data.provider_message_id" class="font-mono text-xs opacity-60 truncate block max-w-[120px]" :title="data.provider_message_id">
                                    {{ data.provider_message_id }}
                                </span>
                                <span v-else class="text-xs opacity-40">—</span>
                            </template>
                        </Column>
                    </DataTable>
                </template>
            </Card>

        </template>
    </div>
</template>
