// ==================== COUNTRIES MANAGEMENT ====================
// Base URL for countries API – adjust if your serverURL already includes /v1/
// If serverURL = "https://demo2.bsl.co.ke/api/v1/", then serverURL_V might need to be "https://demo2.bsl.co.ke/api/"
// For simplicity, we define a separate variable here. Change as needed.
// const serverURL_V = "https://demo2.bsl.co.ke/api/"; // without /v1/

// Main function to load and display all countries
function allCountries() {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="countries-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;
    $(".crud_section").html(loadingHTML);

    // Fetch countries – note the endpoint includes pagination params
    $.ajax({
        url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc',
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        success: function(response) {
            // Handle both paginated response and direct array
            let countries = [];
            if (response.content) {
                countries = response.content; // Spring paginated response
            } else if (Array.isArray(response)) {
                countries = response;
            }
            renderCountriesTable(countries);
        },
        error: function(xhr, status, error) {
            console.error("Error loading countries:", error);
            $(".crud_section").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626;"></i>
                    <h3 style="color: #1a1f36;">Failed to load countries</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allCountries()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Render the countries table
function renderCountriesTable(countries) {
    const total = countries.length;

    var html = `
    <div class="countries-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
        
        <!-- Header Section -->
        <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-globe" style="color: #000;"></i>
                        Countries Management
                    </h1>
                    <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                        ${total} Total
                    </span>
                </div>
                <div style="display: flex; gap: 12px;">
                    <button onclick="addCountry()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #000; color: white; border: none; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-plus"></i> Add Country
                    </button>
                    <button onclick="exportCountries()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #ffffff; color: #1a1f36; border: 1px solid #d0d5dd; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-download"></i> Export
                    </button>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px;">
            <!-- Total Card -->
            <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                <div style="width: 48px; height: 48px; background: #f0f2f5; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin: 0 auto 12px;">
                    <i class="fas fa-globe" style="font-size: 24px; color: #000;"></i>
                </div>
                <div style="font-size: 28px; font-weight: 700; color: #1a1f36;">${total}</div>
                <div style="font-size: 14px; color: #5b677c;">Total Countries</div>
            </div>
        </div>

        <!-- Search and Controls -->
        <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
            <div style="position: relative; flex: 1; max-width: 400px;">
                <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                <input type="text" id="countrySearch" placeholder="Search by code, name, or nationality..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none;">
            </div>
            <div style="display: flex; gap: 12px;">
                <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                    <option value="10">10 per page</option>
                    <option value="25">25 per page</option>
                    <option value="50">50 per page</option>
                    <option value="100">100 per page</option>
                </select>
                <button onclick="allCountries()" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer;">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>

        <!-- Countries Table -->
        <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
            <table class="countries-table" id="countrytableview" style="width: 100%; border-collapse: collapse; min-width: 800px;">
                <thead>
                    <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 60px;">#</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Code</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Country Name</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Nationality</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                    </tr>
                </thead>
                <tbody id="countryTableBody">
    `;

    countries.forEach((country, i) => {
        html += `
        <tr data-country-id="${country.id}" style="border-bottom: 1px solid #eaeef2;">
            <td style="padding: 16px; color: #5b677c;">${i + 1}</td>
            <td style="padding: 16px; font-weight: 600; color: #1a1f36;">${country.code || 'N/A'}</td>
            <td style="padding: 16px;">${country.name || 'N/A'}</td>
            <td style="padding: 16px;">${country.nationality || 'N/A'}</td>
            <td style="padding: 16px; text-align: center;">
                <div class="action-dropdown" style="position: relative; display: inline-block;">
                    <button onclick="toggleCountryActionMenu(${country.id})" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer;">
                        <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                    </button>
                    <div id="country_menu_${country.id}" style="display: none; position: absolute; right: 0; top: 45px; width: 180px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                        <div style="padding: 12px; border-bottom: 1px solid #eaeef2;">
                            <span style="font-weight: 600; color: #1a1f36;">Actions</span>
                        </div>
                        <div style="padding: 8px;">
                            <button onclick='viewCountryDetails(${country.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                <i class="fas fa-eye"></i> View
                            </button>
                            <button onclick='editCountry(${country.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button onclick='deleteCountry(${country.id}, "${country.name}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
        `;
    });

    html += `
                </tbody>
            </table>
        </div>

        <!-- Table Footer -->
        <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
            <div style="color: #5b677c;">
                <span id="selectedCount">0</span> items selected
            </div>
            <div class="table-pagination" id="tablePagination"></div>
        </div>

        <style>
            .countries-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
            .action-dropdown button:hover { background: #f0f2f5; }
        </style>
    </div>
    `;

    $(".crud_section").html(html);

    // Initialize DataTable
    const table = $('#countrytableview').DataTable({
        dom: 'rtip',
        pageLength: 10,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        order: [[0, 'asc']],
        columnDefs: [
            { orderable: false, targets: [4] }
        ]
    });

    // Search
    $('#countrySearch').off('keyup').on('keyup', function() {
        table.search(this.value).draw();
    });

    // Page size
    $('#pageSize').off('change').on('change', function() {
        table.page.len(this.value).draw();
    });

    // Select All (not used but kept for consistency)
    function updateSelectedCount() {
        $("#selectedCount").text($(".row-checkbox:checked").length);
    }
}

// Toggle action menu
function toggleCountryActionMenu(countryId) {
    $('[id^="country_menu_"]').hide();
    $(`#country_menu_${countryId}`).toggle();
}

// ---------- Add Country ----------
function addCountry() {
    showCountryModal('add', null);
}

// Show Add/Edit modal
function showCountryModal(mode, countryData) {
    const isEdit = mode === 'edit';
    const title = isEdit ? 'Edit Country' : 'Add New Country';

    Swal.fire({
        title: title,
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <!-- Country Code -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Country Code <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-barcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="countryCode" placeholder="e.g., KE" value="${isEdit ? countryData.code || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Country Name -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Country Name <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-globe" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="countryName" placeholder="e.g., Kenya" value="${isEdit ? countryData.name || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Nationality -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Nationality <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-flag" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="countryNationality" placeholder="e.g., Kenyan" value="${isEdit ? countryData.nationality || '' : ''}" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>
            </div>

            <style>
                input:focus {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: isEdit ? 'Update Country' : 'Create Country',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '600px',
        preConfirm: () => {
            const code = $('#countryCode').val();
            const name = $('#countryName').val();
            const nationality = $('#countryNationality').val();

            if (!code) {
                Swal.showValidationMessage('Country code is required');
                return false;
            }
            if (!name) {
                Swal.showValidationMessage('Country name is required');
                return false;
            }
            if (!nationality) {
                Swal.showValidationMessage('Nationality is required');
                return false;
            }

            return {
                code: code.trim(),
                name: name.trim(),
                nationality: nationality.trim()
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            if (isEdit) {
                updateCountry(countryData.id, result.value);
            } else {
                createCountry(result.value);
            }
        }
    });
}

// Create country
function createCountry(data) {
    Swal.fire({
        title: 'Creating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL_V + 'countries',
        type: 'POST',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Country created successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allCountries());
        },
        error: function(xhr) {
            let msg = 'Creation failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Edit country – fetch details then show modal
function editCountry(countryId) {
    Swal.fire({
        title: 'Loading...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL_V + 'countries/' + countryId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(country) {
            Swal.close();
            showCountryModal('edit', country);
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not fetch country details',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Update country
function updateCountry(countryId, data) {
    Swal.fire({
        title: 'Updating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL_V + 'countries/' + countryId,
        type: 'PUT',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Country updated successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allCountries());
        },
        error: function(xhr) {
            let msg = 'Update failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Delete country
function deleteCountry(countryId, countryName) {
    Swal.fire({
        title: 'Delete Country?',
        html: `Are you sure you want to delete <strong>${countryName || 'this country'}</strong>?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        confirmButtonText: 'Yes, delete',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleting...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            $.ajax({
                url: serverURL_V + 'countries/' + countryId,
                type: 'DELETE',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function() {
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Country has been removed.',
                        icon: 'success',
                        confirmButtonColor: '#000'
                    }).then(() => allCountries());
                },
                error: function(xhr) {
                    let msg = 'Deletion failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({
                        title: 'Error',
                        text: msg,
                        icon: 'error',
                        confirmButtonColor: '#000'
                    });
                }
            });
        }
    });
}

// View details (simple)
function viewCountryDetails(countryId) {
    $.ajax({
        url: serverURL_V + 'countries/' + countryId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(country) {
            Swal.fire({
                title: 'Country Details',
                html: `<pre style="text-align: left; background: #f8fafc; padding: 16px; border-radius: 8px;">${JSON.stringify(country, null, 2)}</pre>`,
                confirmButtonColor: '#000',
                width: '600px'
            });
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not fetch details',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Export countries (JSON)
function exportCountries() {
    const table = $('#countrytableview').DataTable();
    const data = table.data().toArray();
    const jsonStr = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `countries_export_${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
}

// Initialize on document ready
$(document).ready(function() {
    allCountries();

    $(document).on('click', function(e) {
        if (!$(e.target).closest('.action-dropdown').length) {
            $('[id^="country_menu_"]').hide();
        }
    });
});