@extends('layouts.developer')

@section('title', 'Application Monitoring')

@section('content')
<div x-data="monitoringManager()" x-init="init()" class="space-y-6">
    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Application Monitoring</h1>
            <p class="text-gray-500">Real-time monitoring for tenant and system performance</p>
        </div>
        <div class="flex items-center gap-3">
            <template x-if="selectedTenant !== 'system' && stats?.users?.list">
                <div class="relative inline-block w-48">
                    <select 
                        x-model="selectedUser" 
                        class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-purple-500 focus:border-purple-500 sm:text-sm rounded-md shadow-sm"
                    >
                        <option value="all">👥 All Users</option>
                        <template x-for="user in stats.users.list" :key="user.id">
                            <option :value="user.id" x-text="user.name"></option>
                        </template>
                    </select>
                </div>
            </template>
            <div class="relative inline-block w-64">
                <select 
                    x-model="selectedTenant" 
                    @change="selectedUser = 'all'; loadData()"
                    class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-purple-500 focus:border-purple-500 sm:text-sm rounded-md shadow-sm"
                >
                    <option value="system">🏢 System Wide</option>
                    <optgroup label="Tenants">
                        @foreach($tenants as $tenant)
                            <option value="{{ $tenant->id }}">👤 {{ $tenant->name }}</option>
                        @endforeach
                    </optgroup>
                </select>
            </div>
            <button 
                @click="loadData()" 
                class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500"
                :disabled="loading"
            >
                <span x-show="!loading">🔄 Refresh</span>
                <span x-show="loading" class="flex items-center">
                    <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Updating...
                </span>
            </button>
            <div class="flex items-center gap-2 text-sm text-gray-500">
                <label class="flex items-center cursor-pointer">
                    <input type="checkbox" x-model="autoRefresh" class="rounded text-purple-600 focus:ring-purple-500 mr-2">
                    Auto-refresh (30s)
                </label>
            </div>
        </div>
    </div>

    <!-- Stats Overview -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <!-- User Details (Conditional) -->
        <template x-if="selectedTenant !== 'system' && selectedUser !== 'all'">
            <div class="col-span-4 bg-purple-50 p-4 rounded-lg border border-purple-200 flex items-center justify-between shadow-sm">
                <div class="flex items-center gap-4">
                    <div class="h-12 w-12 bg-purple-600 rounded-full flex items-center justify-center text-white text-xl font-bold">
                        <span x-text="(stats.selected_user_info?.name || stats.users.list.find(u => u.id == selectedUser)?.name || 'U').charAt(0)"></span>
                    </div>
                    <div>
                        <h4 class="text-lg font-bold text-purple-900" x-text="stats.selected_user_info?.name || stats.users.list.find(u => u.id == selectedUser)?.name"></h4>
                        <p class="text-sm text-purple-700" x-text="stats.selected_user_info?.email || stats.users.list.find(u => u.id == selectedUser)?.email"></p>
                    </div>
                </div>
                <div class="text-right">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800" x-text="stats.selected_user_info?.last_active ? 'Last active: ' + stats.selected_user_info.last_active : 'Selected Tenant User'">
                    </span>
                </div>
            </div>
        </template>

        <!-- Template for dynamic stats -->
        <template x-if="selectedTenant === 'system' && stats">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 col-span-4">
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Tenants</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.tenant_stats.total"></div>
                    <div class="mt-1 text-sm text-green-600" x-text="stats.tenant_stats.active + ' active'"></div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Total Users</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.tenant_stats.total_users"></div>
                    <div class="mt-1 text-sm text-gray-500">Across all tenants</div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Memory Usage</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.system.memory_usage"></div>
                    <div class="mt-1 text-sm text-gray-500" x-text="'PHP ' + stats.system.php_version"></div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Active Queries</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats?.active_queries?.length || 0"></div>
                    <div class="mt-1 text-sm text-gray-500">System-wide</div>
                </div>
            </div>
        </template>

        <template x-if="selectedTenant !== 'system' && stats">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 col-span-4">
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Tenant Status</div>
                    <div class="mt-2 flex items-center">
                        <span 
                            class="px-3 py-1 text-sm font-semibold rounded-full"
                            :class="{
                                'bg-green-100 text-green-800': stats.tenant.status === 'active',
                                'bg-yellow-100 text-yellow-800': stats.tenant.status === 'trialing' || stats.tenant.status === 'maintenance',
                                'bg-red-100 text-red-800': stats.tenant.status === 'expired'
                            }"
                            x-text="stats.tenant.status.toUpperCase()"
                        ></span>
                    </div>
                    <div class="mt-1 text-sm text-gray-500" x-text="stats.tenant.domain"></div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Database Size</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.database.size + ' MB'"></div>
                    <div class="mt-1 text-sm text-gray-500" x-text="stats.database.total_tables + ' tables'"></div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Tenant Users</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.users.total"></div>
                    <div class="mt-1 text-sm text-blue-600" x-text="stats.users.active_last_24h + ' active today'"></div>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <div class="text-sm font-medium text-gray-500 uppercase tracking-wider">Active Queries</div>
                    <div class="mt-2 text-3xl font-bold text-gray-900" x-text="stats.active_queries.length"></div>
                    <div class="mt-1 text-sm text-gray-500">Currently processing</div>
                </div>
            </div>
        </template>
    </div>

    <!-- Main Content Area -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Recent Logs -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 flex flex-col h-[500px]">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-900">Recent Application Logs</h3>
                <a :href="selectedTenant === 'system' ? '{{ route('developer.logs') }}' : '{{ route('developer.tenants.activity', ['id' => '__ID__']) }}'.replace('__ID__', selectedTenant)" class="text-sm text-purple-600 hover:text-purple-800 font-medium">View All</a>
            </div>
            <div class="flex-1 overflow-y-auto p-4 space-y-3">
                <template x-if="!stats || !stats.logs || stats.logs.length === 0">
                    <div class="flex flex-col items-center justify-center h-full text-gray-500">
                        <span class="text-4xl mb-2">📄</span>
                        <p>No recent logs found</p>
                    </div>
                </template>
                <template x-for="log in stats?.logs || []" :key="log.timestamp + log.message">
                    <div class="p-3 rounded border" :class="{
                        'border-red-200 bg-red-50': log.level === 'error' || log.level === 'critical',
                        'border-yellow-200 bg-yellow-50': log.level === 'warning',
                        'border-blue-200 bg-blue-50': log.level === 'info',
                        'border-gray-200 bg-gray-50': log.level !== 'error' && log.level !== 'warning' && log.level !== 'info'
                    }">
                        <div class="flex items-center justify-between mb-1">
                            <span class="text-xs font-bold uppercase" :class="{
                                'text-red-700': log.level === 'error' || log.level === 'critical',
                                'text-yellow-700': log.level === 'warning',
                                'text-blue-700': log.level === 'info',
                                'text-gray-700': log.level !== 'error' && log.level !== 'warning' && log.level !== 'info'
                            }" x-text="log.level"></span>
                            <span class="text-xs text-gray-500" x-text="new Date(log.timestamp).toLocaleString()"></span>
                        </div>
                        <p class="text-sm text-gray-800 break-words" x-text="log.message"></p>
                    </div>
                </template>
            </div>
        </div>

        <!-- Database Activity / Queries -->
        <div id="active-queries-section" class="bg-white rounded-lg shadow-sm border border-gray-200 flex flex-col h-[500px]">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-900" x-text="selectedTenant === 'system' ? 'System Overview & Queries' : 'Active Database Queries'"></h3>
                <span x-show="stats?.active_queries?.length > 0" class="px-2 py-1 text-xs font-bold bg-red-600 text-white rounded-full" x-text="stats.active_queries.length + ' Active'"></span>
            </div>
            <div class="flex-1 overflow-y-auto p-4">
                <template x-if="selectedTenant === 'system'">
                    <div class="space-y-6 mb-8 pb-6 border-b border-gray-100">
                        <div class="grid grid-cols-2 gap-4">
                            <div class="p-4 bg-purple-50 rounded-lg border border-purple-100">
                                <div class="text-xs font-bold text-purple-700 uppercase mb-1">Laravel Version</div>
                                <div class="text-xl font-bold text-gray-900" x-text="stats?.system?.laravel_version || 'Loading...'"></div>
                            </div>
                            <div class="p-4 bg-blue-50 rounded-lg border border-blue-100">
                                <div class="text-xs font-bold text-blue-700 uppercase mb-1">PHP Version</div>
                                <div class="text-xl font-bold text-gray-900" x-text="stats?.system?.php_version || 'Loading...'"></div>
                            </div>
                        </div>
                        
                        <div>
                            <h4 class="text-sm font-bold text-gray-700 uppercase mb-3">Tenant Distribution</h4>
                            <div class="space-y-3">
                                <div class="relative pt-1">
                                    <div class="flex mb-2 items-center justify-between">
                                        <div>
                                            <span class="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-green-600 bg-green-200">Active</span>
                                        </div>
                                        <div class="text-right">
                                            <span class="text-xs font-semibold inline-block text-green-600" x-text="Math.round((stats?.tenant_stats?.active / stats?.tenant_stats?.total) * 100) + '%'"></span>
                                        </div>
                                    </div>
                                    <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-green-200">
                                        <div :style="'width: ' + ((stats?.tenant_stats?.active / stats?.tenant_stats?.total) * 100) + '%'" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-green-500"></div>
                                    </div>
                                </div>
                                <div class="relative pt-1">
                                    <div class="flex mb-2 items-center justify-between">
                                        <div>
                                            <span class="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-yellow-600 bg-yellow-200">Trialing</span>
                                        </div>
                                        <div class="text-right">
                                            <span class="text-xs font-semibold inline-block text-yellow-600" x-text="Math.round((stats?.tenant_stats?.trialing / stats?.tenant_stats?.total) * 100) + '%'"></span>
                                        </div>
                                    </div>
                                    <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-yellow-200">
                                        <div :style="'width: ' + ((stats?.tenant_stats?.trialing / stats?.tenant_stats?.total) * 100) + '%'" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-yellow-500"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>

                <div class="space-y-4">
                    <template x-if="selectedTenant === 'system' && stats?.active_queries?.length > 0">
                        <h4 class="text-sm font-bold text-gray-700 uppercase mb-3">Active System Queries</h4>
                    </template>

                    <template x-if="(!stats || !stats.active_queries || stats.active_queries.length === 0) && selectedTenant !== 'system'">
                        <div class="flex flex-col items-center justify-center h-full text-gray-500 pt-10">
                            <span class="text-4xl mb-2">⚡</span>
                            <p>No active long-running queries</p>
                        </div>
                    </template>

                    <template x-for="query in stats?.active_queries || []" :key="query.ID">
                        <div class="p-4 border border-red-100 rounded-lg hover:bg-red-50 transition">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs font-mono font-bold bg-red-50 text-red-700 border border-red-100 px-2 py-1 rounded" x-text="'ID: ' + query.ID"></span>
                                <span class="text-xs text-red-600 font-bold" x-text="query.TIME + 's'"></span>
                            </div>
                            <div class="text-sm font-mono text-red-700 break-all bg-white border border-red-200 p-2 rounded mb-2 overflow-x-auto shadow-sm" x-text="query.INFO || 'No query info'"></div>
                            <div class="flex items-center gap-4 text-xs text-gray-500">
                                <span class="flex items-center gap-1">👤 <span class="font-medium text-red-600" x-text="query.USER"></span></span>
                                <span class="flex items-center gap-1">📍 <span x-text="query.HOST"></span></span>
                                <span class="flex items-center gap-1">📊 <span class="text-red-500" x-text="query.STATE"></span></span>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function monitoringManager() {
    return {
        selectedTenant: 'system',
        selectedUser: 'all',
        stats: null,
        loading: false,
        autoRefresh: true,
        refreshInterval: null,

        async init() {
            // Check for view=queries parameter
            const urlParams = new URLSearchParams(window.location.search);
            
            if (urlParams.get('tenant_id')) {
                this.selectedTenant = urlParams.get('tenant_id');
            }

            if (urlParams.get('view') === 'queries') {
                this.$nextTick(() => {
                    const el = document.getElementById('active-queries-section');
                    if (el) el.scrollIntoView({ behavior: 'smooth' });
                });
            }
            
            await this.loadData();
            this.refreshInterval = setInterval(() => {
                if (this.autoRefresh && !this.loading) {
                    this.loadData();
                }
            }, 30000); // 30 seconds
        },

        async loadData() {
            this.loading = true;
            try {
                const url = new URL(`{{ route('developer.monitoring.data') }}`, window.location.origin);
                url.searchParams.append('tenant_id', this.selectedTenant);
                if (this.selectedUser !== 'all') {
                    url.searchParams.append('user_id', this.selectedUser);
                }
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.success) {
                    this.stats = result.data;
                } else {
                    alert('Error: ' + result.message);
                }
            } catch (error) {
                console.error('Monitoring Error:', error);
            } finally {
                this.loading = false;
            }
        }
    }
}
</script>
@endsection
