<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, router, usePage } from '@inertiajs/vue3';
import { onMounted, onUnmounted } from 'vue';

const props = defineProps({
    queues: Array
});

const page = usePage();
const userTenantId = page.props.auth.user.tenant_id;

let channel = null;

onMounted(() => {
    if (userTenantId) {
        if (window.Echo) {
            connectToChannel();
        } else {
            const checkEcho = setInterval(() => {
                if (window.Echo) {
                    clearInterval(checkEcho);
                    connectToChannel();
                }
            }, 100);
        }
    }
});

const connectToChannel = () => {
    console.log(`📡 Conectando ao canal dashboard.${userTenantId}...`);

    channel = window.Echo.private(`dashboard.${userTenantId}`)
        .listen('.metrics.updated', (e) => {
            console.log("🔔 Evento recebido!", e);
            router.reload({ only: ['queues'], preserveScroll: true });
        })
        .error((err) => {
            console.error("❌ Erro de Conexão/Auth:", err);
        });
};

onUnmounted(() => {
    if (userTenantId && window.Echo) {
        console.log(`🔌 Desconectando do canal dashboard.${userTenantId}`);
        window.Echo.leave(`dashboard.${userTenantId}`);
    }
});

const formatTime = (seconds) => {
    if (!seconds && seconds !== 0) return '-';
    const m = Math.floor(seconds / 60).toString().padStart(2, '0');
    const s = (seconds % 60).toString().padStart(2, '0');
    return `${m}:${s}`;
};

const calculatePercentage = (part, total) => {
    if (!total || total === 0) return '0.0%';
    const percent = (part / total) * 100;
    return `${percent.toFixed(1)}%`;
};
</script>

<template>

    <Head title="Dashboard" />

    <AuthenticatedLayout>
        <template #header>
            <h2 class="text-xl font-bold text-gray-800">
                Dashboard
            </h2>
        </template>

        <div class="py-8">
            <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">

                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col"
                                        class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">
                                        Fila / Canal
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">
                                        Total (Dia)
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">
                                        Em Fila (Agora)
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">
                                        TME (Espera)
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-center text-xs font-bold text-gray-500 uppercase tracking-wider">
                                        TMA (Conversa)
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-4 text-center text-xs font-bold text-red-600 uppercase tracking-wider">
                                        Abandonados
                                    </th>
                                </tr>
                            </thead>

                            <tbody class="bg-white divide-y divide-gray-200">
                                <tr v-for="queue in queues" :key="queue.id"
                                    class="hover:bg-gray-50 transition duration-150">

                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-shrink-0 h-8 w-8 flex items-center justify-center rounded-full"
                                                :class="queue.type === 'voice' ? 'bg-blue-100 text-blue-600' : 'bg-green-100 text-green-600'">
                                                <svg v-if="queue.type === 'voice'" class="w-4 h-4" fill="none"
                                                    stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z">
                                                    </path>
                                                </svg>
                                                <svg v-else class="w-4 h-4" fill="none" stroke="currentColor"
                                                    viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z">
                                                    </path>
                                                </svg>
                                            </div>
                                            <div class="ml-3">
                                                <div class="text-sm font-semibold text-gray-900">{{ queue.name }}</div>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-bold text-gray-900">
                                        {{ queue.daily_metrics[0]?.received_count || 0 }}
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-center">
                                        <div class="flex flex-col items-center">
                                            <div v-if="queue.waiting_list.length > 0"
                                                class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 mb-1">
                                                <span
                                                    class="w-2 h-2 mr-1.5 bg-red-500 rounded-full animate-pulse"></span>
                                                {{ queue.waiting_list.length }}
                                            </div>
                                            <div v-else class="text-sm text-gray-400 mb-1">-</div>

                                            <span
                                                v-if="queue.daily_metrics[0]?.received_count > 0 && queue.waiting_list.length > 0"
                                                class="text-[10px] text-gray-400">
                                                {{ calculatePercentage(queue.waiting_list.length,
                                                    queue.daily_metrics[0]?.received_count) }} do vol.
                                            </span>
                                        </div>
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-600">
                                        {{ formatTime(queue.daily_metrics[0]?.avg_wait_time || 0) }}
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-600">
                                        {{ formatTime(queue.daily_metrics[0]?.avg_talk_time || 0) }}
                                    </td>

                                    <td class="px-6 py-4 whitespace-nowrap text-center">
                                        <div class="flex flex-col items-center justify-center">
                                            <span class="text-sm font-bold"
                                                :class="(queue.daily_metrics[0]?.abandoned_count || 0) > 0 ? 'text-red-600' : 'text-gray-400'">
                                                {{ queue.daily_metrics[0]?.abandoned_count || 0 }}
                                            </span>

                                            <span
                                                class="text-xs font-medium mt-0.5 px-2 py-0.5 rounded bg-gray-100 text-gray-500">
                                                {{ calculatePercentage(queue.daily_metrics[0]?.abandoned_count || 0,
                                                    queue.daily_metrics[0]?.received_count || 0) }}
                                            </span>
                                        </div>
                                    </td>

                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

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