<x-app-layout>
    <x-module-hero
        title="Google Meet Activity Logs"
        description="View all Google Meet API interactions and their status"
        icon="fa-history">
        <x-slot name="tabs">
            <a href="{{ route('config.google-meet.index') }}"
               class="module-hero-tab {{ request()->routeIs('config.google-meet.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a href="{{ route('config.google-meet.create') }}"
               class="module-hero-tab {{ request()->routeIs('config.google-meet.create') || request()->routeIs('config.google-meet.edit') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-cog"></i> Configuration
            </a>
            <a href="{{ route('config.google-meet.test') }}"
               class="module-hero-tab {{ request()->routeIs('config.google-meet.test') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-plug"></i> Test Connection
            </a>
            <a href="{{ route('config.google-meet.logs') }}"
               class="module-hero-tab {{ request()->routeIs('config.google-meet.logs') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-history"></i> Activity Logs
            </a>
            <a href="{{ route('config.google-meet.documentation') }}"
               class="module-hero-tab {{ request()->routeIs('config.google-meet.documentation') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
                <i class="fas fa-book"></i> Documentation
            </a>
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        {{-- Filters --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-6 p-4">
            <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                <i class="fas fa-filter text-gray-500"></i> Filter Logs
            </h3>
            <form method="GET" action="{{ route('config.google-meet.logs') }}"
                  class="grid grid-cols-1 md:grid-cols-5 gap-4">
                <div>
                    <label for="type" class="block text-xs font-medium text-gray-700 mb-1">Type</label>
                    <select name="type" id="type"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                        <option value="">All Types</option>
                        <option value="create_meeting" {{ request('type') === 'create_meeting' ? 'selected' : '' }}>Create Meeting</option>
                        <option value="test" {{ request('type') === 'test' ? 'selected' : '' }}>Test Connection</option>
                        <option value="token_refresh" {{ request('type') === 'token_refresh' ? 'selected' : '' }}>Token Refresh</option>
                        <option value="revoke_access" {{ request('type') === 'revoke_access' ? 'selected' : '' }}>Revoke Access</option>
                    </select>
                </div>
                <div>
                    <label for="status" class="block text-xs font-medium text-gray-700 mb-1">Status</label>
                    <select name="status" id="status"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                        <option value="">All Status</option>
                        <option value="success" {{ request('status') === 'success' ? 'selected' : '' }}>Success</option>
                        <option value="failed" {{ request('status') === 'failed' ? 'selected' : '' }}>Failed</option>
                    </select>
                </div>
                <div>
                    <label for="date_from" class="block text-xs font-medium text-gray-700 mb-1">Date From</label>
                    <input type="date" name="date_from" id="date_from"
                           value="{{ request('date_from') }}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                </div>
                <div>
                    <label for="date_to" class="block text-xs font-medium text-gray-700 mb-1">Date To</label>
                    <input type="date" name="date_to" id="date_to"
                           value="{{ request('date_to') }}"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                </div>
                <div class="flex items-end gap-2">
                    <button type="submit"
                            class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm">
                        <i class="fas fa-search mr-1"></i> Filter
                    </button>
                    <a href="{{ route('config.google-meet.logs') }}"
                       class="px-3 py-2 border border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50 transition text-sm">
                        <i class="fas fa-times"></i>
                    </a>
                </div>
            </form>
        </div>

        {{-- Logs Table --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h2 class="text-base font-semibold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-list text-gray-500"></i>
                    Log Entries
                    <span class="text-sm font-normal text-gray-500">({{ $logs->total() }} total)</span>
                </h2>
                @if($logs->total() > 0)
                    <span class="text-xs text-gray-500">
                        Showing {{ $logs->firstItem() }}–{{ $logs->lastItem() }} of {{ $logs->total() }}
                    </span>
                @endif
            </div>

            @if($logs->count() > 0)
                <div class="overflow-x-auto">
                    <table class="w-full table-zebra">
                        <thead>
                            <tr>
                                <th class="px-4 py-3 text-left th-col-1 text-white text-xs font-semibold uppercase tracking-wider">Date/Time</th>
                                <th class="px-4 py-3 text-left th-col-2 text-white text-xs font-semibold uppercase tracking-wider">Type</th>
                                <th class="px-4 py-3 text-left th-col-3 text-white text-xs font-semibold uppercase tracking-wider">Status</th>
                                <th class="px-4 py-3 text-left th-col-4 text-white text-xs font-semibold uppercase tracking-wider">Summary</th>
                                <th class="px-4 py-3 text-left th-col-5 text-white text-xs font-semibold uppercase tracking-wider">Attendees</th>
                                <th class="px-4 py-3 text-left th-col-6 text-white text-xs font-semibold uppercase tracking-wider">Duration</th>
                                <th class="px-4 py-3 text-left th-col-7 text-white text-xs font-semibold uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($logs as $log)
                                <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                    <td class="px-4 py-3 text-sm">
                                        <div class="text-gray-900">{{ $log->created_at->format('M d, Y') }}</div>
                                        <div class="text-xs text-gray-500">{{ $log->created_at->format('H:i:s') }}</div>
                                    </td>
                                    <td class="px-4 py-3 text-sm">
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium
                                            @if($log->type === 'create_meeting') bg-blue-100 text-blue-800
                                            @elseif($log->type === 'test') bg-purple-100 text-purple-800
                                            @elseif($log->type === 'token_refresh') bg-yellow-100 text-yellow-800
                                            @else bg-gray-100 text-gray-800 @endif">
                                            {{ $log->getTypeLabel() }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm">
                                        @if($log->isSuccessful())
                                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-check-circle mr-1"></i> Success
                                            </span>
                                        @else
                                            <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                <i class="fas fa-times-circle mr-1"></i> Failed
                                            </span>
                                        @endif
                                    </td>
                                    <td class="px-4 py-3 text-sm">
                                        <div class="text-gray-900 max-w-xs truncate" title="{{ $log->summary }}">
                                            {{ $log->summary ?? '-' }}
                                        </div>
                                        @if($log->meeting_link)
                                            <a href="{{ $log->meeting_link }}" target="_blank"
                                               class="text-xs text-blue-600 hover:underline">
                                                <i class="fas fa-external-link-alt mr-1"></i> View Meeting
                                            </a>
                                        @endif
                                        @if($log->error_message)
                                            <div class="text-xs text-red-600 mt-0.5 truncate" title="{{ $log->error_message }}">
                                                {{ $log->error_message }}
                                            </div>
                                        @endif
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-500">
                                        @if($log->attendees_count)
                                            <span class="inline-flex items-center gap-1">
                                                <i class="fas fa-users text-xs"></i> {{ $log->attendees_count }}
                                            </span>
                                        @else
                                            <span class="text-gray-400">-</span>
                                        @endif
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-500">
                                        <span class="inline-flex items-center gap-1">
                                            <i class="fas fa-clock text-xs"></i>
                                            {{ $log->getFormattedExecutionTime() }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm">
                                        <button type="button"
                                                onclick="showLogDetails({{ $log->id }}, {{ json_encode($log->response_body) }}, '{{ addslashes($log->error_message ?? '') }}')"
                                                class="btn-action-view">
                                            <i class="fas fa-eye"></i> View
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="px-4 py-3 border-t border-gray-200">
                    {{ $logs->appends(request()->query())->links() }}
                </div>
            @else
                <div class="p-12 text-center">
                    <i class="fas fa-inbox text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No logs found</h3>
                    <p class="text-gray-500 text-sm">
                        @if(request()->hasAny(['type', 'status', 'date_from', 'date_to']))
                            No logs match your filter criteria. Try adjusting your filters.
                        @else
                            No activity logs yet. Configure and test your Google Meet integration to start logging.
                        @endif
                    </p>
                    @if(!request()->hasAny(['type', 'status', 'date_from', 'date_to']))
                        <a href="{{ route('config.google-meet.test') }}"
                           class="inline-block mt-4 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm">
                            <i class="fas fa-plug mr-1"></i> Test Connection
                        </a>
                    @endif
                </div>
            @endif
        </div>

        {{-- Summary Stats --}}
        @if($logs->count() > 0)
            <div class="mt-6 grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Total Operations</p>
                    <p class="text-2xl font-bold mt-1 text-blue-600">{{ $logs->total() }}</p>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Success Rate</p>
                    <p class="text-2xl font-bold mt-1 text-green-600">
                        {{ $logs->count() > 0 ? round(($logs->where('status', 'success')->count() / $logs->count()) * 100) : 0 }}%
                    </p>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Avg Duration</p>
                    <p class="text-2xl font-bold mt-1 text-purple-600">
                        {{ $logs->avg('execution_time_ms') ? round($logs->avg('execution_time_ms')) : 0 }}ms
                    </p>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Failed</p>
                    <p class="text-2xl font-bold mt-1 text-red-600">
                        {{ $logs->where('status', 'failed')->count() }}
                    </p>
                </div>
            </div>
        @endif
    </div>

    {{-- Log Details Modal --}}
    <div id="logModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50 overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-5xl w-full overflow-hidden">
                <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 rounded-t-lg">
                    <h3 class="text-base font-semibold text-white flex items-center gap-2">
                        <i class="fas fa-info-circle"></i> Log Details
                    </h3>
                    <button type="button" onclick="closeLogModal()" class="text-white/80 hover:text-white transition">
                        <i class="fas fa-times text-lg"></i>
                    </button>
                </div>
                <div id="logDetails" class="p-6"></div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function showLogDetails(logId, responseBody, errorMessage) {
            const modal = document.getElementById('logModal');
            const details = document.getElementById('logDetails');
            let html = '';
            if (errorMessage) {
                html += `<div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                    <p class="text-sm font-medium text-red-800">Error Message</p>
                    <p class="text-sm text-red-700 mt-1">${errorMessage}</p>
                </div>`;
            }
            if (responseBody) {
                html += `<div>
                    <p class="text-sm font-medium text-gray-800 mb-2">API Response</p>
                    <pre class="bg-gray-50 border border-gray-200 rounded-lg p-3 text-xs overflow-x-auto">${JSON.stringify(responseBody, null, 2)}</pre>
                </div>`;
            }
            if (!html) {
                html = `<p class="text-gray-500 text-sm">No additional details available for log #${logId}.</p>`;
            }
            details.innerHTML = html;
            modal.classList.remove('hidden');
        }
        function closeLogModal() {
            document.getElementById('logModal').classList.add('hidden');
        }
        document.getElementById('logModal').addEventListener('click', function(e) {
            if (e.target === this) closeLogModal();
        });
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') closeLogModal();
        });
    </script>
    @endpush
</x-app-layout>
