@extends('layouts.layoutadmin')
@section('title', 'Manajemen Admin')

@section('content')
    <div class="admin-dashboard">
        @include('admin.components.sidebar')

        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Manajemen Admin</div>
                    <div class="subtitle">Kelola Data Admin</div>
                </div>
                <div class="header-actions">
                    <a href="feedback"><i class="fas fa-bell"></i></a>
                    <a href="pengaturan-situs"><i class="fas fa-cog"></i></a>
                    <form method="POST" action="{{ route('logout') }}" style="display:inline;">
                        @csrf
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>

            <div class="main-content">
                <div class="content-wrapper">
                    <div class="admin-container">
                        <div id="alert-container"></div>

                        <!-- Tabel Daftar Admin -->
                        <div class="table-container">
                            <div class="table-header">
                                <h3>Daftar Admin</h3>
                                <a href="{{ route('admin.kelolaAdmin') }}" class="btn-primary">
                                    <i class="fas fa-plus"></i> Tambah Admin
                                </a>
                            </div>
                            <table class="admin-table">
                                <thead>
                                    <tr>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Phone</th>
                                        <th>Site ID</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="adminTableBody">
                                    <!-- Data akan diisi melalui JavaScript -->
                                </tbody>
                            </table>
                        </div>

                        <!-- Modal Edit Admin -->
                        <div id="editModal" class="modal">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h3>Edit Admin</h3>
                                    <span class="close">&times;</span>
                                </div>
                                <form id="editAdminForm">
                                    <input type="hidden" id="editAdminId">
                                    <div class="form-group">
                                        <label for="editEmail">Email</label>
                                        <input type="email" id="editEmail" name="email" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="editRoleDisplay">Role</label>
                                        <input type="text" id="editRoleDisplay" readonly>
                                        <input type="hidden" id="editRole" name="role">
                                    </div>
                                    <div class="form-group">
                                        <label for="editPhone">Nomor Telepon</label>
                                        <input type="tel" id="editPhone" name="phone" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="editSiteId">Site ID</label>
                                        <input type="number" id="editSiteId" name="site_id" min="1" max="25"
                                            required>
                                    </div>
                                    <div class="form-group">
                                        <label for="editPassword">Password</label>
                                        <input type="password" id="editPassword" name="password" required
                                            pattern="^(?=.*[A-Z])(?=.*[!@#$%^&*(),.?\":{}|<>])(?=.*[0-9]).{8,}$"
                                            title="Password harus minimal 8 karakter, mengandung huruf kapital, angka, dan karakter spesial">
                                        <small class="password-hint">Password harus minimal 8 karakter, mengandung huruf
                                            kapital, angka, dan karakter spesial</small>
                                    </div>
                                    <div class="form-actions">
                                        <button type="submit" class="btn-primary">
                                            <i class="fas fa-save"></i> Simpan
                                        </button>
                                        <button type="button" class="btn-secondary" onclick="closeEditModal()">
                                            <i class="fas fa-times"></i> Batal
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <style>
        /* Styles sama dengan kelolaAdmin.blade.php */
        body {
            background: #f4f4f4;
        }

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .sidebar-footer {
            padding: 18px 24px;
            border-top: 1px solid #333;
            background: #23272b;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.98rem;
        }

        .sidebar-footer .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #444;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .sidebar-footer .user-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .sidebar-footer .user-info span {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }

        .sidebar-footer .user-info small {
            color: #bfc5c9;
            font-size: 0.95rem;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }
        
        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .main-header .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .main-header .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .main-header .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .main-header .header-actions button {
            background: #d72660;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
        }

        .main-header .header-actions button:hover {
            background: #b61f50;
        }

        .main-header .header-actions i {
            font-size: 1.3rem;
            color: #535963;
            background: #f4f4f4;
            border-radius: 50%;
            padding: 6px;
            margin-right: 2px;
            cursor: pointer;
        }

        .main-content {
            padding: 32px;
        }

        .btn-primary {
            background: #22c1b6;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary:hover {
            background: #1dada3;
        }

        .btn-secondary {
            background: #f3f4f6;
            color: #374151;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-secondary:hover {
            background: #e5e7eb;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            animation: slideIn 0.3s ease-out;
            transition: opacity 0.3s;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        @keyframes slideIn {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-error {
            background-color: #fee2e2;
            color: #b91c1c;
            border-left: 4px solid #ef4444;
            font-weight: 500;
        }

        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .admin-container {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            padding: 32px;
            width: 100%;
        }

        .table-container {
            margin-top: 20px;
        }

        .admin-table {
            width: 100%;
            border-collapse: collapse;
        }

        .admin-table th {
            background: #f8f9fa;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 2px solid #e5e7eb;
        }

        .admin-table td {
            padding: 12px;
            border-bottom: 1px solid #e5e7eb;
            color: #6b7280;
        }

        .admin-table tr:hover {
            background: #f8f9fa;
        }

        .btn-edit,
        .btn-delete {
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .btn-edit {
            background: #22c1b6;
            color: #fff;
        }

        .btn-delete {
            background: #ef4444;
            color: #fff;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            overflow-y: auto;
        }

        .modal-content {
            background: #fff;
            margin: 5% auto;
            border-radius: 12px;
            width: 500px;
            max-width: 90%;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            animation: modalFadeIn 0.3s ease-out;
            position: relative;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 24px;
            border-bottom: 1px solid #e5e7eb;
            background-color: #f8f9fa;
            border-radius: 12px 12px 0 0;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 1.25rem;
            color: #1f2937;
        }

        .close {
            font-size: 28px;
            font-weight: 700;
            color: #6b7280;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close:hover {
            color: #111827;
        }

        #editAdminForm {
            padding: 24px;
        }

        #editAdminForm .form-group {
            margin-bottom: 18px;
        }

        #editAdminForm label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        #editAdminForm input,
        #editAdminForm select {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.2s;
            background-color: #fff;
        }

        #editAdminForm input:focus,
        #editAdminForm select:focus {
            border-color: #22c1b6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(34, 193, 182, 0.2);
        }

        #editAdminForm input[readonly] {
            background-color: #f3f4f6;
            cursor: not-allowed;
            color: #6b7280;
            border-color: #d1d5db;
        }

        .password-hint {
            display: block;
            font-size: 0.85rem;
            color: #6b7280;
            margin-top: 4px;
            font-style: italic;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 24px;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }
    </style>

    <script>
        // Function to get auth token
        function getAuthToken() {
            // First try to get token from Laravel session
            const sessionToken = '{{ session('auth.token') ?? '' }}';
            if (sessionToken) {
                console.log('Using token from Laravel session');
                return sessionToken;
            }

            // Fall back to browser storage
            const token = localStorage.getItem('auth_token') ||
                localStorage.getItem('token') ||
                localStorage.getItem('access_token') ||
                sessionStorage.getItem('auth_token') ||
                sessionStorage.getItem('token') ||
                sessionStorage.getItem('access_token');

            if (token) {
                console.log('Using token from browser storage');
                return token;
            }

            console.warn('No authentication token found');
            return null;
        }

        // Penanganan session expired global (jaga-jaga jika belum ada)
        if (typeof window.handleSessionExpired !== 'function') {
            window.handleSessionExpired = function() {
                if (window.sessionExpiredHandled) return;
                window.sessionExpiredHandled = true;
                alert('Session Anda telah habis. Silakan login ulang.');
                window.location.href = '/login';
            };
        }

        // Load admin data
        async function loadAdminData() {
            try {
                const token = getAuthToken();
                if (!token) {
                    throw new Error('Token autentikasi tidak ditemukan');
                }

                const response = await fetch('{{ env('AUTH_API_BASE_URL') }}/api/admin/user-admin', {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.status === 401) {
                    if (window.handleSessionExpired) window.handleSessionExpired();
                    return;
                }

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || 'Gagal memuat data admin');
                }

                const tableBody = document.getElementById('adminTableBody');
                tableBody.innerHTML = '';

                data.admins.forEach(admin => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${admin.email}</td>
                        <td>${admin.role}</td>
                        <td>${admin.phone}</td>
                        <td>${admin.site_id}</td>
                        <td class="action-buttons">
                            <button class="btn-edit" onclick='openEditModal(${JSON.stringify(admin)})'>
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn-delete" onclick="deleteAdmin('${admin.id}')">
                                <i class="fas fa-trash"></i> Hapus
                            </button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } catch (error) {
                showAlert(error.message, 'error');
            }
        }

        // Show alert message with improved HTML handling
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');

            // Create alert element
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;

            // Add icon based on type
            const icon = type === 'success' ?
                '<i class="fas fa-check-circle" style="margin-right: 10px;"></i>' :
                '<i class="fas fa-exclamation-circle" style="margin-right: 10px;"></i>';

            // Handle message that might contain HTML (from API errors)
            if (message.includes('<br>')) {
                // For messages with <br> tags, create a proper DOM structure
                const messageContainer = document.createElement('div');
                messageContainer.innerHTML = message;

                // Create the full content with icon
                alertDiv.innerHTML = icon;
                alertDiv.appendChild(messageContainer);
            } else {
                // Simple message without HTML
                alertDiv.innerHTML = `${icon}${message}`;
            }

            // Clear existing alerts
            alertContainer.innerHTML = '';

            // Add the new alert
            alertContainer.appendChild(alertDiv);

            // Auto dismiss after 5 seconds unless it's an error
            if (type !== 'error') {
                setTimeout(() => {
                    alertDiv.style.opacity = '0';
                    setTimeout(() => {
                        if (alertContainer.contains(alertDiv)) {
                            alertContainer.removeChild(alertDiv);
                        }
                    }, 300);
                }, 5000);
            }
        }

        // Edit modal functions
        function openEditModal(admin) {
            // Debug the admin object to see what fields we're receiving
            console.log('Admin data received:', admin);

            // Display the modal
            document.getElementById('editModal').style.display = 'block';

            try {
                // Set form values with validation
                document.getElementById('editAdminId').value = admin.id;
                document.getElementById('editEmail').value = admin.email || '';

                // Set role in both hidden field and display field
                const roleValue = admin.role || 'admin';
                document.getElementById('editRole').value = roleValue;
                document.getElementById('editRoleDisplay').value = roleValue.charAt(0).toUpperCase() + roleValue.slice(
                    1); // Capitalize first letter

                document.getElementById('editPhone').value = admin.phone || '';
                document.getElementById('editSiteId').value = admin.site_id || '';

                // Reset password field to empty - user must enter a new password
                document.getElementById('editPassword').value = '';

                // Validate that we have all required fields
                if (!admin.id || !admin.email) {
                    console.error('Missing required admin data', admin);
                    showAlert('Data admin tidak lengkap', 'error');
                }

                // Add event listener to close button
                document.querySelector('.close').addEventListener('click', closeEditModal);
            } catch (error) {
                console.error('Error setting form values:', error);
                showAlert('Error mempersiapkan form edit: ' + error.message, 'error');
            }
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // Update admin
        document.getElementById('editAdminForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            // Get form values
            const adminId = document.getElementById('editAdminId').value;
            const email = document.getElementById('editEmail').value.trim();
            const role = document.getElementById('editRole').value.trim() || 'admin';
            const phone = document.getElementById('editPhone').value.trim();
            const siteIdStr = document.getElementById('editSiteId').value.trim();
            const password = document.getElementById('editPassword').value;

            // Validate inputs
            if (!email) {
                showAlert('Email tidak boleh kosong', 'error');
                return;
            }

            if (!phone) {
                showAlert('Nomor telepon tidak boleh kosong', 'error');
                return;
            }

            if (!siteIdStr || isNaN(parseInt(siteIdStr))) {
                showAlert('Site ID harus berupa angka', 'error');
                return;
            }

            const siteId = parseInt(siteIdStr);
            if (siteId < 1 || siteId > 25) {
                showAlert('Site ID harus antara 1-25', 'error');
                return;
            }

            // Validate password
            if (!password) {
                showAlert('Password tidak boleh kosong', 'error');
                return;
            }

            const passwordRegex = /^(?=.*[A-Z])(?=.*[!@#$%^&*(),.?":{}|<>])(?=.*[0-9]).{8,}$/;
            if (!passwordRegex.test(password)) {
                showAlert(
                    'Password minimal 8 karakter dan harus mengandung huruf kapital, angka, dan spesial karakter',
                    'error');
                return;
            }

            // Prepare data for API with password included
            const data = {
                email: email,
                role: role,
                phone: phone,
                site_id: siteId,
                password: password // Use the validated password from above
            };

            console.log('Submitting data:', data);

            try {
                const token = getAuthToken();
                if (!token) {
                    throw new Error('Token autentikasi tidak ditemukan');
                }

                // Show loading indicator
                showAlert('Menyimpan perubahan...', 'success');

                // Send API request with debugging headers
                console.log('Sending request to API with data:', data);

                const response = await fetch(`{{ env('AUTH_API_BASE_URL') }}/api/admin/user-admin/${adminId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(data)
                });

                if (response.status === 401) {
                    if (window.handleSessionExpired) window.handleSessionExpired();
                    return;
                }

                console.log('Raw API response status:', response.status, response.statusText);
                const result = await response.json();
                console.log('API response body:', result);

                if (!response.ok) {
                    // More detailed error handling with better debugging
                    console.error('API error details:', result);

                    if (result.message) {
                        // Check if it's a password validation error
                        if (result.message.includes('password') || result.message.toLowerCase().includes(
                                'karakter')) {
                            // Focus the password field
                            document.getElementById('editPassword').focus();
                        }
                        throw new Error(result.message);
                    } else if (result.errors) {
                        // Handle validation errors
                        const errorMessages = Object.values(result.errors).flat().join('<br>');

                        // Check if there are password errors
                        if (errorMessages.toLowerCase().includes('password')) {
                            // Focus the password field
                            document.getElementById('editPassword').focus();
                        }

                        throw new Error(errorMessages || 'Terjadi kesalahan validasi');
                    } else {
                        throw new Error(`Gagal mengupdate admin: ${response.status} ${response.statusText}`);
                    }
                }

                // Success handling
                showAlert('Admin berhasil diupdate');
                closeEditModal();
                loadAdminData();
            } catch (error) {
                console.error('Update error:', error);
                // Show full error message for debugging
                showAlert(`Error: ${error.message}`, 'error');
            }
        });

        // Delete admin
        async function deleteAdmin(adminId) {
            if (!confirm('Apakah Anda yakin ingin menghapus admin ini?')) {
                return;
            }

            try {
                const token = getAuthToken();
                if (!token) {
                    throw new Error('Token autentikasi tidak ditemukan');
                }

                const response = await fetch(`{{ env('AUTH_API_BASE_URL') }}/api/admin/user-admin/${adminId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.status === 401) {
                    if (window.handleSessionExpired) window.handleSessionExpired();
                    return;
                }

                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.message || 'Gagal menghapus admin');
                }

                showAlert('Admin berhasil dihapus');
                loadAdminData();
            } catch (error) {
                showAlert(error.message, 'error');
            }
        }

        // Load data when page loads
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Page loaded, initializing admin management');

            try {
                // Check for authentication token
                const token = getAuthToken();
                if (token) {
                    console.log('Authentication token found, loading admin data');
                    loadAdminData();
                } else {
                    console.error('No authentication token found');
                    showAlert('Token autentikasi tidak ditemukan. Silakan login ulang.', 'error');
                }

                // Add event listener for all close buttons
                const closeButtons = document.querySelectorAll('.close');
                closeButtons.forEach(button => {
                    button.addEventListener('click', closeEditModal);
                });

                // Add event listener for closing modal when clicking outside
                window.addEventListener('click', function(event) {
                    const modal = document.getElementById('editModal');
                    if (event.target === modal) {
                        closeEditModal();
                    }
                });

                // Setup form validation
                const editForm = document.getElementById('editAdminForm');
                if (editForm) {
                    console.log('Edit form found and initialized');
                } else {
                    console.error('Edit form element not found!');
                }
            } catch (error) {
                console.error('Error during initialization:', error);
                showAlert('Terjadi kesalahan saat memuat halaman: ' + error.message, 'error');
            }
        });

        // // Sidebar dropdown toggle
        // document.getElementById('kelola-admin-link').addEventListener('click', function(e) {
        //     e.preventDefault();
        //     var dropdown = document.getElementById('kelola-admin-dropdown');
        //     dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
        // });

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('editModal');
            if (event.target == modal) {
                closeEditModal();
            }
        }
    </script>
@endsection
