<x-app-layout>
    <x-module-hero
        title="Email Configuration"
        description="Manage SMTP/IMAP settings and test email connectivity"
        icon="fa-envelope-circle-check">
        <x-slot name="tabs">
            @can('view email configuration')
            <a href="{{ route('config.email.index') }}"
               class="module-hero-tab {{ request()->routeIs('config.email.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>
            @endcan
            @can('create email configuration')
            <a href="{{ route('config.email.create') }}"
               class="module-hero-tab {{ request()->routeIs('config.email.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>
            @endcan
            @can('edit email configuration')
            @if($configuration)
            <a href="{{ route('config.email.edit') }}"
               class="module-hero-tab {{ request()->routeIs('config.email.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>
            @endif
            @endcan
            @can('view email logs')
            <a href="{{ route('config.email.logs') }}"
               class="module-hero-tab {{ request()->routeIs('config.email.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>
            @endcan
            <a href="{{ route('config.email.documentation') }}"
               class="module-hero-tab {{ request()->routeIs('config.email.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">
            @can('test email configuration')
                <button onclick="testSmtpConnection()"
                        class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-white rounded bg-blue-600 hover:bg-blue-700 transition-colors {{ !$status['smtp_configured'] ? 'opacity-50 cursor-not-allowed' : '' }}"
                        {{ !$status['smtp_configured'] ? 'disabled' : '' }}>
                    <i class="fas fa-plug"></i> Test SMTP
                </button>
                <button onclick="testImapConnection()"
                        class="inline-flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-white rounded bg-purple-600 hover:bg-purple-700 transition-colors {{ !$status['imap_configured'] ? 'opacity-50 cursor-not-allowed' : '' }}"
                        {{ !$status['imap_configured'] ? 'disabled' : '' }}>
                    <i class="fas fa-plug"></i> Test IMAP
                </button>
                <button onclick="openTestEmailModal()"
                        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 {{ !$status['smtp_configured'] ? 'opacity-50 cursor-not-allowed' : '' }}"
                        {{ !$status['smtp_configured'] ? 'disabled' : '' }}>
                    <i class="fas fa-paper-plane"></i> Send Test Email
                </button>
            @endcan
        </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">SMTP</p>
                <p class="text-xl font-bold mt-1 {{ $status['smtp_configured'] ? 'text-green-600' : 'text-gray-400' }}">
                    {{ $status['smtp_configured'] ? 'Ready' : 'Not Set' }}
                </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">IMAP</p>
                <p class="text-xl font-bold mt-1 {{ $status['imap_configured'] ? 'text-green-600' : 'text-gray-400' }}">
                    {{ $status['imap_configured'] ? 'Ready' : 'Not Set' }}
                </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 Emails</p>
                <p class="text-xl font-bold mt-1 text-blue-600">{{ $logStats['total'] ?? 0 }}</p>
            </div>
        </div>

        <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> Current Configuration
                        </h2>
                    </div>
                    <div class="p-6">
                        @if($configuration)
                            <div class="space-y-4">
                                {{-- SMTP --}}
                                <div class="border border-gray-200 rounded-lg p-4">
                                    <h3 class="font-medium text-gray-800 mb-3 flex items-center gap-2">
                                        <i class="fas fa-paper-plane text-blue-500"></i> SMTP Settings
                                    </h3>
                                    <dl class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <div>
                                            <dt class="text-xs text-gray-500">Host</dt>
                                            <dd class="font-medium text-gray-800">{{ $configuration->smtp_host }}</dd>
                                        </div>
                                        <div>
                                            <dt class="text-xs text-gray-500">Port</dt>
                                            <dd class="font-medium text-gray-800">{{ $configuration->smtp_port }}</dd>
                                        </div>
                                        <div>
                                            <dt class="text-xs text-gray-500">Encryption</dt>
                                            <dd class="font-medium text-gray-800">{{ strtoupper($configuration->smtp_encryption) }}</dd>
                                        </div>
                                        <div>
                                            <dt class="text-xs text-gray-500">Username</dt>
                                            <dd class="font-medium text-gray-800">{{ $configuration->smtp_username ?? 'Not set' }}</dd>
                                        </div>
                                    </dl>
                                </div>

                                {{-- IMAP --}}
                                <div class="border border-gray-200 rounded-lg p-4">
                                    <h3 class="font-medium text-gray-800 mb-3 flex items-center gap-2">
                                        <i class="fas fa-inbox text-purple-500"></i> IMAP Settings
                                    </h3>
                                    @if($configuration->hasImapConfigured())
                                        <dl class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                            <div>
                                                <dt class="text-xs text-gray-500">Host</dt>
                                                <dd class="font-medium text-gray-800">{{ $configuration->imap_host }}</dd>
                                            </div>
                                            <div>
                                                <dt class="text-xs text-gray-500">Port</dt>
                                                <dd class="font-medium text-gray-800">{{ $configuration->imap_port }}</dd>
                                            </div>
                                            <div>
                                                <dt class="text-xs text-gray-500">Encryption</dt>
                                                <dd class="font-medium text-gray-800">{{ strtoupper($configuration->imap_encryption) }}</dd>
                                            </div>
                                            <div>
                                                <dt class="text-xs text-gray-500">Username</dt>
                                                <dd class="font-medium text-gray-800">{{ $configuration->imap_username ?? 'Not set' }}</dd>
                                            </div>
                                        </dl>
                                    @else
                                        <p class="text-gray-500 italic text-sm">IMAP not configured</p>
                                    @endif
                                </div>

                                {{-- Sender Info --}}
                                <div class="border border-gray-200 rounded-lg p-4">
                                    <h3 class="font-medium text-gray-800 mb-3 flex items-center gap-2">
                                        <i class="fas fa-user text-green-500"></i> Sender Information
                                    </h3>
                                    <dl class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <div>
                                            <dt class="text-xs text-gray-500">From Address</dt>
                                            <dd class="font-medium text-gray-800">{{ $configuration->from_address ?? 'Not set' }}</dd>
                                        </div>
                                        <div>
                                            <dt class="text-xs text-gray-500">From Name</dt>
                                            <dd class="font-medium text-gray-800">{{ $configuration->from_name ?? 'Not set' }}</dd>
                                        </div>
                                    </dl>
                                </div>

                                @can('edit email configuration')
                                    <div class="flex gap-2 pt-2">
                                        <a href="{{ route('config.email.edit') }}"
                                           class="btn-action-edit">
                                            <i class="fas fa-edit"></i> Edit Configuration
                                        </a>
                                    </div>
                                @endcan
                            </div>
                        @else
                            <div class="text-center py-8">
                                <i class="fas fa-envelope-open text-gray-300 text-5xl mb-4"></i>
                                <h3 class="text-lg font-medium text-gray-900 mb-2">No Configuration Found</h3>
                                <p class="text-gray-500 mb-4 text-sm">Set up your email configuration to enable email functionality.</p>
                                @can('create email configuration')
                                    <a href="{{ route('config.email.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> Create Configuration
                                    </a>
                                @endcan
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Right Sidebar --}}
            <div class="space-y-4">
                {{-- Statistics --}}
                <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">Success Rate</dt>
                            <dd class="font-medium text-green-600">{{ $logStats['success_rate'] ?? 0 }}%</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">Today</dt>
                            <dd class="font-medium">{{ $logStats['today'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">This Week</dt>
                            <dd class="font-medium">{{ $logStats['this_week'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">This Month</dt>
                            <dd class="font-medium">{{ $logStats['this_month'] ?? 0 }}</dd>
                        </div>
                        <div class="flex justify-between text-sm">
                            <dt class="text-gray-500">Avg Execution</dt>
                            <dd class="font-medium">{{ $logStats['avg_execution_time'] ?? 0 }}ms</dd>
                        </div>
                    </dl>
                </div>

                {{-- Recent Activity --}}
                <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>
                    @if($recentLogs->count() > 0)
                        <div class="space-y-2">
                            @foreach($recentLogs as $log)
                                <div class="flex items-center justify-between py-1.5 border-b border-gray-100 last:border-0">
                                    <div>
                                        <span class="inline-block px-2 py-0.5 text-xs rounded-full {{ $log->status_badge }}">
                                            {{ ucfirst($log->status) }}
                                        </span>
                                        <span class="text-xs text-gray-600 ml-1">{{ $log->type_label }}</span>
                                    </div>
                                    <span class="text-xs text-gray-400">{{ $log->time_ago }}</span>
                                </div>
                            @endforeach
                        </div>
                        <div class="mt-3">
                            <a href="{{ route('config.email.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>
                    @else
                        <p class="text-gray-500 text-xs">No recent activity</p>
                    @endif
                </div>
            </div>
        </div>
    </div>

    {{-- Test Email Modal --}}
    <div id="testEmailModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-md w-full overflow-hidden">
                <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-teal-600 to-teal-700 rounded-t-lg">
                    <h3 class="text-base font-semibold text-white flex items-center gap-2">
                        <i class="fas fa-paper-plane"></i> Send Test Email
                    </h3>
                    <button type="button" onclick="closeTestEmailModal()" class="text-white/80 hover:text-white transition">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-6">
                    <form id="testEmailForm">
                        @csrf
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Recipient Email</label>
                            <input type="email" name="email" id="testEmailAddress"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
                                   placeholder="test@example.com" required>
                        </div>
                        <div class="flex justify-end gap-2">
                            <button type="button" onclick="closeTestEmailModal()"
                                    class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">
                                Cancel
                            </button>
                            <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-paper-plane mr-1"></i> Send Test
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    {{-- Connection Test Result Modal --}}
    <div id="testResultModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-md 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" id="testResultTitle">
                        <i class="fas fa-plug"></i> Connection Test Result
                    </h3>
                    <button type="button" onclick="closeTestResultModal()" class="text-white/80 hover:text-white transition">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-6">
                    <div id="testResultContent" class="mb-4"></div>
                    <div class="flex justify-end">
                        <button type="button" onclick="closeTestResultModal()"
                                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>

    @push('scripts')
    <script>
        function testSmtpConnection() {
            fetch('{{ route("config.email.test") }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                body: JSON.stringify({ type: 'smtp' })
            }).then(r => r.json()).then(d => showTestResult('SMTP', d)).catch(e => showTestResult('SMTP', { success: false, error: e.message }));
        }
        function testImapConnection() {
            fetch('{{ route("config.email.test") }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                body: JSON.stringify({ type: 'imap' })
            }).then(r => r.json()).then(d => showTestResult('IMAP', d)).catch(e => showTestResult('IMAP', { success: false, error: e.message }));
        }
        function showTestResult(type, result) {
            document.getElementById('testResultTitle').textContent = type + ' Connection Test';
            const content = document.getElementById('testResultContent');
            if (result.success) {
                content.innerHTML = `<div class="bg-green-50 border border-green-200 rounded-lg p-4"><div class="flex items-center mb-2"><i class="fas fa-check-circle text-green-500 text-xl mr-2"></i><span class="font-medium text-green-800">Connection Successful</span></div><p class="text-sm text-green-700">${result.message}</p><p class="text-xs text-green-600 mt-2">Execution time: ${result.execution_time_ms}ms</p></div>`;
            } else {
                content.innerHTML = `<div class="bg-red-50 border border-red-200 rounded-lg p-4"><div class="flex items-center mb-2"><i class="fas fa-times-circle text-red-500 text-xl mr-2"></i><span class="font-medium text-red-800">Connection Failed</span></div><p class="text-sm text-red-700">${result.message || result.error}</p></div>`;
            }
            document.getElementById('testResultModal').classList.remove('hidden');
        }
        function closeTestResultModal() { document.getElementById('testResultModal').classList.add('hidden'); }
        function openTestEmailModal() { document.getElementById('testEmailModal').classList.remove('hidden'); }
        function closeTestEmailModal() { document.getElementById('testEmailModal').classList.add('hidden'); }
        document.getElementById('testEmailForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const email = document.getElementById('testEmailAddress').value;
            fetch('{{ route("config.email.test-email") }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                body: JSON.stringify({ email: email })
            }).then(r => r.json()).then(d => { closeTestEmailModal(); showTestResult('Email', d); }).catch(e => { closeTestEmailModal(); showTestResult('Email', { success: false, error: e.message }); });
        });
    </script>
    @endpush
</x-app-layout>
