<x-app-layout>
    <x-module-hero
        title="SMS Logs"
        description="View and analyze SMS message history"
        icon="fa-history">
        <x-slot name="tabs">
            <a href="{{ route('config.sms.index') }}"
               class="module-hero-tab text-[#1e293b]">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a href="{{ route('config.sms.edit') }}"
               class="module-hero-tab text-[#1e293b]">
                <i class="fas fa-edit"></i> Edit Configuration
            </a>
            <a href="{{ route('config.sms.logs') }}"
               class="module-hero-tab active-tab text-[#1e293b]">
                <i class="fas fa-history"></i> Logs
            </a>
            <a href="{{ route('config.sms.documentation') }}"
               class="module-hero-tab text-[#1e293b]">
                <i class="fas fa-book"></i> Documentation
            </a>
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        {{-- Stats Row --}}
        <div class="grid grid-cols-1 md:grid-cols-5 gap-4 mb-6">
            <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</p>
                <p class="text-2xl font-bold mt-1 text-blue-600">{{ $statistics['total'] ?? 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">Sent</p>
                <p class="text-2xl font-bold mt-1 text-blue-500">{{ $statistics['sent'] ?? 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">Delivered</p>
                <p class="text-2xl font-bold mt-1 text-green-600">{{ $statistics['delivered'] ?? 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">Failed</p>
                <p class="text-2xl font-bold mt-1 text-red-600">{{ $statistics['failed'] ?? 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">Today</p>
                <p class="text-2xl font-bold mt-1 text-purple-600">{{ $statistics['today'] ?? 0 }}</p>
            </div>
        </div>

        {{-- Filters --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-4">
            <form method="GET" action="{{ route('config.sms.logs') }}">
                <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">Search</label>
                        <input type="text" name="search" value="{{ request('search') }}"
                               placeholder="Phone or message..."
                               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 class="block text-xs font-medium text-gray-700 mb-1">Status</label>
                        <select name="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 Statuses</option>
                            <option value="pending" {{ request('status') === 'pending' ? 'selected' : '' }}>Pending</option>
                            <option value="sent" {{ request('status') === 'sent' ? 'selected' : '' }}>Sent</option>
                            <option value="delivered" {{ request('status') === 'delivered' ? 'selected' : '' }}>Delivered</option>
                            <option value="failed" {{ request('status') === 'failed' ? 'selected' : '' }}>Failed</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-700 mb-1">From Date</label>
                        <input type="date" name="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 class="block text-xs font-medium text-gray-700 mb-1">To Date</label>
                        <input type="date" name="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="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.sms.logs') }}"
                           class="px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </div>
            </form>
        </div>

        {{-- Logs Table --}}
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"
             x-data="logModalComponent()">
            <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                <h2 class="text-sm font-semibold text-gray-800 flex items-center gap-2">
                    <i class="fas fa-list text-green-600"></i> SMS History
                    <span class="text-gray-400 font-normal">({{ $logs->total() }} records)</span>
                </h2>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left th-col-1">Recipient</th>
                            <th class="px-4 py-3 text-left th-col-2">Message</th>
                            <th class="px-4 py-3 text-left th-col-3">Status</th>
                            <th class="px-4 py-3 text-left th-col-4">Segments</th>
                            <th class="px-4 py-3 text-left th-col-5">Cost</th>
                            <th class="px-4 py-3 text-left th-col-6">Date</th>
                            <th class="px-4 py-3 text-center th-col-7">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($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 whitespace-nowrap text-sm font-medium text-gray-800">
                                    {{ $log->recipient }}
                                </td>
                                <td class="px-4 py-3">
                                    <div class="text-sm text-gray-700 max-w-xs truncate">{{ $log->message }}</div>
                                    <div class="text-xs text-gray-400">{{ $log->message_length ?? strlen($log->message) }} chars</div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium
                                        {{ $log->status === 'delivered' ? 'bg-green-100 text-green-800' :
                                           ($log->status === 'sent' ? 'bg-blue-100 text-blue-800' :
                                           ($log->status === 'failed' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800')) }}">
                                        {{ ucfirst($log->status) }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                    {{ $log->segment_count ?? 1 }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                    {{ $log->cost ? '$' . number_format($log->cost, 4) : '-' }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                    <div>{{ $log->created_at->format('M d, Y') }}</div>
                                    <div class="text-xs text-gray-400">{{ $log->created_at->format('H:i:s') }}</div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-center">
                                    <button @click="showLogDetails({{ $log->id }})"
                                            class="btn-action-view">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="px-4 py-12 text-center">
                                    <i class="fas fa-inbox text-gray-300 text-4xl mb-4"></i>
                                    <p class="text-gray-500">No SMS logs found</p>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            @if($logs->hasPages())
                <div class="p-4 border-t border-gray-200">
                    {{ $logs->appends(request()->query())->links() }}
                </div>
            @endif

            {{-- Log Details Modal --}}
            <div x-show="showModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 z-50" style="display:none;">
                <div class="flex items-center justify-center min-h-screen p-4">
                    <div class="bg-white rounded-lg shadow-xl max-w-lg w-full overflow-hidden"
                         x-transition:enter="transition ease-out duration-200"
                         x-transition:enter-start="opacity-0 scale-95"
                         x-transition:enter-end="opacity-100 scale-100">
                        <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> SMS Log Details
                            </h3>
                            <button @click="closeModal()" class="text-white/80 hover:text-white transition">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="p-6">
                        <div class="space-y-3">
                            <div class="grid grid-cols-2 gap-3">
                                <div><p class="text-xs text-gray-500">Recipient</p><p class="font-medium text-gray-800" x-text="logData.recipient"></p></div>
                                <div><p class="text-xs text-gray-500">Status</p>
                                    <span :class="{
                                        'bg-green-100 text-green-800': logData.status === 'delivered',
                                        'bg-blue-100 text-blue-800': logData.status === 'sent',
                                        'bg-red-100 text-red-800': logData.status === 'failed',
                                        'bg-yellow-100 text-yellow-800': logData.status === 'pending'
                                    }" class="inline-block px-2 py-0.5 rounded-full text-xs font-medium" x-text="logData.status?.toUpperCase()"></span>
                                </div>
                            </div>
                            <div><p class="text-xs text-gray-500">Message</p><p class="font-medium text-gray-800 bg-gray-50 rounded p-2 text-sm" x-text="logData.message"></p></div>
                            <div class="grid grid-cols-2 gap-3">
                                <div><p class="text-xs text-gray-500">Message ID</p><p class="font-mono text-xs text-gray-800" x-text="logData.message_id || 'N/A'"></p></div>
                                <div><p class="text-xs text-gray-500">Execution Time</p><p class="font-medium text-gray-800 text-sm" x-text="(logData.execution_time_ms || 0) + ' ms'"></p></div>
                            </div>
                            <div x-show="logData.error_message">
                                <p class="text-xs text-gray-500">Error</p>
                                <p class="text-red-600 bg-red-50 rounded p-2 text-sm" x-text="logData.error_message"></p>
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <div><p class="text-xs text-gray-500">Sent By</p><p class="font-medium text-gray-800 text-sm" x-text="logData.user || 'System'"></p></div>
                                <div><p class="text-xs text-gray-500">Date</p><p class="font-medium text-gray-800 text-sm" x-text="logData.created_at"></p></div>
                            </div>
                        </div>
                        <div class="mt-4 flex justify-end">
                            <button @click="closeModal()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">Close</button>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function logModalComponent() {
            return {
                showModal: false,
                logData: {},
                async showLogDetails(logId) {
                    try {
                        const response = await fetch(`/config/sms/logs/${logId}`, {
                            headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
                        });
                        const data = await response.json();
                        if (data.success) { this.logData = data.data; this.showModal = true; }
                    } catch (error) { console.error('Failed to fetch log details:', error); }
                },
                closeModal() { this.showModal = false; this.logData = {}; }
            }
        }
    </script>
    @endpush
</x-app-layout>
