// ==================== PORTS MANAGEMENT ====================
// Global variables (assume userObj and serverURL are defined elsewhere)
// serverURL = "https://demo2.bsl.co.ke/api/v1/"

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

    // Modern loading skeleton
    var loadingHTML = `
        <div class="ports-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 ports
    $.ajax({
        url: serverURL + 'ports',
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        success: function(ports) {
            // ports is an array of { id, code, name, countryId? } – from sample response, it's just code, name, countryId
            // But the GET /ports might return objects with id, code, name, countryId. We'll assume each has id.
            const data = ports || [];

            // Also fetch countries to display country names in the table
            loadCountryMap(function(countryMap) {
                renderPortsTable(data, countryMap);
            });
        },
        error: function(xhr, status, error) {
            console.error("Error loading ports:", 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 ports</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allPorts()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Helper: load countries and return a map id -> name
function loadCountryMap(callback) {
    $.ajax({
        url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc',
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(response) {
            // response might be a paginated object or array; adapt as needed
            let countries = [];
            if (response.content) {
                countries = response.content; // paginated
            } else if (Array.isArray(response)) {
                countries = response;
            }
            const map = {};
            countries.forEach(c => { map[c.id] = c.name; });
            callback(map);
        },
        error: function() {
            callback({}); // proceed with empty map
        }
    });
}

// Render the ports table
function renderPortsTable(ports, countryMap) {
    const total = ports.length;

    var html = `
    <div class="ports-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-ship" style="color: #000;"></i>
                        Ports 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="addPort()" 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 Port
                    </button>
                    <button onclick="exportPorts()" 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-ship" 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 Ports</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="portSearch" placeholder="Search by code or name..." 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="allPorts()" 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>

        <!-- Ports 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="ports-table" id="porttableview" 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;">Port Name</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Country</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                    </tr>
                </thead>
                <tbody id="portTableBody">
    `;

    ports.forEach((port, i) => {
        const countryName = countryMap[port.countryId] || 'N/A';
        html += `
        <tr data-port-id="${port.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;">${port.code || 'N/A'}</td>
            <td style="padding: 16px;">${port.name || 'N/A'}</td>
            <td style="padding: 16px;">${countryName}</td>
            <td style="padding: 16px; text-align: center;">
                <div class="action-dropdown" style="position: relative; display: inline-block;">
                    <button onclick="togglePortActionMenu(${port.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="port_menu_${port.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='viewPortDetails(${port.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='editPort(${port.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='deletePort(${port.id}, "${port.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>
            .ports-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
            .action-dropdown button:hover { background: #f0f2f5; }
        </style>
    </div>
    `;

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

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

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

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

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

// Toggle action menu
function togglePortActionMenu(portId) {
    $('[id^="port_menu_"]').hide();
    $(`#port_menu_${portId}`).toggle();
}

// ---------- Add Port ----------
function addPort() {
    // Load countries first
    Swal.fire({
        title: 'Loading countries...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc',
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(response) {
            let countries = [];
            if (response.content) countries = response.content;
            else if (Array.isArray(response)) countries = response;

            Swal.close();
            showPortModal('add', null, countries);
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not load country list',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Show Add/Edit modal
function showPortModal(mode, portData, countries) {
    const isEdit = mode === 'edit';
    const title = isEdit ? 'Edit Port' : 'Add New Port';

    // Build country dropdown options
    let countryOptions = '<option value="">Select a country</option>';
    countries.forEach(c => {
        countryOptions += `<option value="${c.id}" ${isEdit && portData.countryId == c.id ? 'selected' : ''}>${c.name}</option>`;
    });

    Swal.fire({
        title: title,
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <!-- Port Code -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Port 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="portCode" placeholder="e.g., MOMBA" value="${isEdit ? portData.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>

                <!-- Port Name -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Port Name <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-ship" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="text" id="portName" placeholder="e.g., Mombasa" value="${isEdit ? portData.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>

                <!-- Country Dropdown -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Country <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>
                        <select id="portCountry" 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; background: white; appearance: none;">
                            ${countryOptions}
                        </select>
                        <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                    </div>
                </div>
            </div>

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

            if (!code) {
                Swal.showValidationMessage('Port code is required');
                return false;
            }
            if (!name) {
                Swal.showValidationMessage('Port name is required');
                return false;
            }
            if (!countryId) {
                Swal.showValidationMessage('Please select a country');
                return false;
            }

            return {
                code: code.trim(),
                name: name.trim(),
                countryId: parseInt(countryId)
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            if (isEdit) {
                updatePort(portData.id, result.value);
            } else {
                createPort(result.value);
            }
        }
    });
}

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

    $.ajax({
        url: serverURL + 'ports',
        type: 'POST',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Port created successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allPorts());
        },
        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 port – fetch details then show modal
function editPort(portId) {
    Swal.fire({
        title: 'Loading...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    // Fetch port details (assuming GET /ports/{id})
    $.ajax({
        url: serverURL + 'ports/' + portId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(port) {
            // Now load countries
            $.ajax({
                url: serverURL_V + 'countries?page=0&size=1000&sort=createdAt,desc',
                type: 'GET',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function(response) {
                    let countries = [];
                    if (response.content) countries = response.content;
                    else if (Array.isArray(response)) countries = response;
                    Swal.close();
                    showPortModal('edit', port, countries);
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'Could not load country list',
                        icon: 'error',
                        confirmButtonColor: '#000'
                    });
                }
            });
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not fetch port details',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Update port
function updatePort(portId, data) {
    Swal.fire({
        title: 'Updating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'ports/' + portId,
        type: 'PUT',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: function() {
            Swal.fire({
                title: 'Success!',
                text: 'Port updated successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allPorts());
        },
        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 port
function deletePort(portId, portName) {
    Swal.fire({
        title: 'Delete Port?',
        html: `Are you sure you want to delete <strong>${portName || 'this port'}</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 + 'ports/' + portId,
                type: 'DELETE',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function() {
                    Swal.fire({
                        title: 'Deleted!',
                        text: 'Port has been removed.',
                        icon: 'success',
                        confirmButtonColor: '#000'
                    }).then(() => allPorts());
                },
                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 viewPortDetails(portId) {
    $.ajax({
        url: serverURL + 'ports/' + portId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(port) {
            Swal.fire({
                title: 'Port Details',
                html: `<pre style="text-align: left; background: #f8fafc; padding: 16px; border-radius: 8px;">${JSON.stringify(port, null, 2)}</pre>`,
                confirmButtonColor: '#000',
                width: '600px'
            });
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not fetch details',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Export ports (JSON)
function exportPorts() {
    const table = $('#porttableview').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 = `ports_export_${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
}

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

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