<x-app-layout>
    <x-module-hero
        title="SMS Configuration"
        description="Manage Africa's Talking API credentials and settings"
        icon="fa-mobile-screen">
        <x-slot name="tabs">
            <a href="{{ route('config.sms.index') }}"
               class="module-hero-tab {{ request()->routeIs('config.sms.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>
            @if($status['configured'])
            <a href="{{ route('config.sms.edit') }}"
               class="module-hero-tab {{ request()->routeIs('config.sms.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-edit"></i> Edit Configuration
            </a>
            @else
            <a href="{{ route('config.sms.create') }}"
               class="module-hero-tab {{ request()->routeIs('config.sms.create') ? '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-plus"></i> New Configuration
            </a>
            @endif
            <a href="{{ route('config.sms.logs') }}"
               class="module-hero-tab {{ request()->routeIs('config.sms.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> Logs
            </a>
            <a href="{{ route('config.sms.documentation') }}"
               class="module-hero-tab {{ request()->routeIs('config.sms.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-slot name="actions">
            @if($status['configured'])
            <button onclick="document.getElementById('testSmsPanel').classList.toggle('hidden')"
                    class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-white rounded bg-teal-600 hover:bg-teal-700 transition-colors">
                <i class="fas fa-vial"></i> Test SMS
            </button>
            @endif
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        {{-- Flash Messages --}}
        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center">
                <i class="fas fa-check-circle mr-2"></i> {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center">
                <i class="fas fa-exclamation-circle mr-2"></i> {{ session('error') }}
            </div>
        @endif

        {{-- Stats Row --}}
        <div class="grid grid-cols-1 md:grid-cols-4 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">Status</p>
                <p class="text-xl font-bold mt-1 {{ $status['configured'] ? 'text-green-600' : 'text-red-500' }}">
                    {{ $status['configured'] ? 'Active' : 'Not Configured' }}
                </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">Environment</p>
                <p class="text-xl font-bold mt-1 {{ ($status['environment'] ?? '') === 'production' ? 'text-green-600' : 'text-yellow-600' }}">
                    {{ ucfirst($status['environment'] ?? 'N/A') }}
                </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">Total Sent</p>
                <p class="text-xl font-bold mt-1 text-blue-600">{{ $statistics['total_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">Today</p>
                <p class="text-xl font-bold mt-1 text-purple-600">{{ $statistics['today_sent'] ?? 0 }}</p>
            </div>
        </div>

        {{-- Test SMS Panel (hidden by default) --}}
        @if($status['configured'])
        <div id="testSmsPanel" class="hidden mb-6 bg-white rounded-lg shadow-sm border border-gray-200 p-4"
             x-data="testSmsComponent()">
            <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                <i class="fas fa-vial text-teal-500"></i> Send Test SMS
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-xs font-medium text-gray-700 mb-1">Phone Number</label>
                    <input type="text" x-model="testPhone" placeholder="+254712345678"
                           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">Message (optional)</label>
                    <input type="text" x-model="testMessage" placeholder="Test 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 class="flex items-end">
                    <button @click="sendTestSms()" :disabled="loading"
                            class="w-full px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition text-sm disabled:opacity-50">
                        <span x-show="!loading"><i class="fas fa-paper-plane mr-1"></i> Send Test</span>
                        <span x-show="loading"><i class="fas fa-spinner fa-spin mr-1"></i> Sending...</span>
                    </button>
                </div>
            </div>
            <div x-show="testResult" x-transition class="mt-3">
                <div x-show="testResult?.success" class="p-3 bg-green-50 border border-green-200 text-green-700 rounded-lg text-sm">
                    <i class="fas fa-check-circle mr-1"></i> <span x-text="testResult?.message"></span>
                </div>
                <div x-show="!testResult?.success" class="p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
                    <i class="fas fa-exclamation-circle mr-1"></i> <span x-text="testResult?.message"></span>
                </div>
            </div>
        </div>
        @endif

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {{-- Configuration Details --}}
            <div class="lg:col-span-2">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="p-4 border-b border-gray-200">
                        <h2 class="text-base font-semibold text-gray-800 flex items-center gap-2">
                            <i class="fas fa-cog text-green-600"></i> Configuration Status
                        </h2>
                    </div>
                    <div class="p-6">
                        @if($status['configured'])
                            <div class="flex items-center mb-4">
                                <span class="flex items-center justify-center w-10 h-10 rounded-full bg-green-100 text-green-600 mr-3">
                                    <i class="fas fa-check"></i>
                                </span>
                                <div>
                                    <h4 class="font-semibold text-gray-800">SMS is Configured</h4>
                                    <p class="text-sm text-gray-500">Africa's Talking API credentials are active</p>
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="bg-gray-50 rounded-lg p-3">
                                    <p class="text-xs text-gray-500 mb-1">Environment</p>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold
                                        {{ ($status['environment'] ?? '') === 'production' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800' }}">
                                        <i class="fas {{ ($status['environment'] ?? '') === 'production' ? 'fa-server' : 'fa-flask' }} mr-1"></i>
                                        {{ ucfirst($status['environment'] ?? 'N/A') }}
                                    </span>
                                </div>
                                <div class="bg-gray-50 rounded-lg p-3">
                                    <p class="text-xs text-gray-500 mb-1">Sender ID</p>
                                    <p class="font-semibold text-gray-800">{{ $status['sender_id'] ?? 'N/A' }}</p>
                                </div>
                                <div class="bg-gray-50 rounded-lg p-3 md:col-span-2">
                                    <p class="text-xs text-gray-500 mb-1">API Status</p>
                                    <span class="inline-flex items-center gap-1 text-sm font-medium
                                        {{ ($apiStatus['status'] ?? '') === 'online' ? 'text-green-600' : (($apiStatus['status'] ?? '') === 'not_configured' ? 'text-yellow-600' : 'text-red-600') }}">
                                        <i class="fas {{ ($apiStatus['status'] ?? '') === 'online' ? 'fa-circle-check' : 'fa-circle-xmark' }}"></i>
                                        {{ $apiStatus['message'] ?? 'Unknown' }}
                                    </span>
                                </div>
                            </div>
                            <div class="flex gap-2 mt-4">
                                <a href="{{ route('config.sms.edit') }}" class="btn-action-edit">
                                    <i class="fas fa-edit"></i> Edit Configuration
                                </a>
                            </div>
                        @else
                            <div class="text-center py-8">
                                <i class="fas fa-mobile-screen text-gray-300 text-5xl mb-4"></i>
                                <h3 class="text-lg font-medium text-gray-900 mb-2">SMS Not Configured</h3>
                                <p class="text-gray-500 mb-4 text-sm">Set up your Africa's Talking API credentials to start sending SMS messages.</p>
                                <a href="{{ route('config.sms.create') }}"
                                   class="inline-flex items-center gap-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm">
                                    <i class="fas fa-plus"></i> Configure SMS
                                </a>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Statistics --}}
            <div class="space-y-4">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-chart-bar text-indigo-500"></i> Statistics
                    </h3>
                    <dl class="space-y-2">
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">Delivered</dt>
                            <dd class="font-medium text-green-600">{{ $statistics['total_delivered'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">Failed</dt>
                            <dd class="font-medium text-red-600">{{ $statistics['total_failed'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">Pending</dt>
                            <dd class="font-medium text-yellow-600">{{ $statistics['total_pending'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">This Month</dt>
                            <dd class="font-medium">{{ $statistics['this_month_sent'] ?? 0 }}</dd>
                        </div>
                    </dl>
                </div>

                {{-- Recent Logs --}}
                @if($recentLogs->count() > 0)
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-clock text-gray-500"></i> Recent Activity
                    </h3>
                    <div class="space-y-2">
                        @foreach($recentLogs->take(5) as $log)
                        <div class="flex items-center justify-between py-1.5 border-b border-gray-100 last:border-0">
                            <div>
                                <span class="text-xs font-medium text-gray-800">{{ $log->recipient }}</span>
                                <span class="ml-1 inline-block px-1.5 py-0.5 text-xs rounded-full
                                    {{ $log->status === 'delivered' ? 'bg-green-100 text-green-800' :
                                       ($log->status === 'failed' ? 'bg-red-100 text-red-800' :
                                       ($log->status === 'sent' ? 'bg-blue-100 text-blue-800' : 'bg-yellow-100 text-yellow-800')) }}">
                                    {{ ucfirst($log->status) }}
                                </span>
                            </div>
                            <span class="text-xs text-gray-400">{{ $log->created_at->diffForHumans() }}</span>
                        </div>
                        @endforeach
                    </div>
                    <div class="mt-3">
                        <a href="{{ route('config.sms.logs') }}" class="text-xs text-green-600 hover:text-green-700">
                            View all logs <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>
                @endif
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function testSmsComponent() {
            return {
                testPhone: '',
                testMessage: '',
                loading: false,
                testResult: null,
                async sendTestSms() {
                    if (!this.testPhone) {
                        this.testResult = { success: false, message: 'Please enter a phone number' };
                        return;
                    }
                    this.loading = true;
                    this.testResult = null;
                    try {
                        const response = await fetch('{{ route("config.sms.test") }}', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                            body: JSON.stringify({ test_phone: this.testPhone, test_message: this.testMessage })
                        });
                        this.testResult = await response.json();
                    } catch (error) {
                        this.testResult = { success: false, message: 'An error occurred: ' + error.message };
                    } finally {
                        this.loading = false;
                    }
                }
            }
        }
    </script>
    @endpush
</x-app-layout>
