// ==================== INSPECTION STATUSES 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 inspection statuses
function allInspectionStatuses() {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="statuses-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 inspection statuses
    $.ajax({
        url: serverURL + 'inspection-statuses',
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        success: function(response) {
            // Response is likely an array directly
            let statuses = response || [];
            renderInspectionStatusesTable(statuses);
        },
        error: function(xhr, status, error) {
            console.error("Error loading inspection statuses:", 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 inspection statuses</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allInspectionStatuses()" 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 inspection statuses table
function renderInspectionStatusesTable(statuses) {
    const total = statuses.length;

    var html = `
    <div class="statuses-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-clipboard-list" style="color: #000;"></i>
                        Inspection Statuses
                    </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="addInspectionStatus()" 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 Status
                    </button>
                    <button onclick="exportInspectionStatuses()" 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-clipboard-list" 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 Statuses</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="statusSearch" placeholder="Search by code, name, or description..." 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="allInspectionStatuses()" 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>

        <!-- Statuses 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="statuses-table" id="statustableview" style="width: 100%; border-collapse: collapse; min-width: 900px;">
                <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;">Name</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Description</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                    </tr>
                </thead>
                <tbody id="statusTableBody">
    `;

    statuses.forEach((status, i) => {
        html += `
        <tr data-status-id="${status.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;">${status.code || 'N/A'}</td>
            <td style="padding: 16px;">${status.name || 'N/A'}</td>
            <td style="padding: 16px;">${status.description || 'N/A'}</td>
            <td style="padding: 16px; text-align: center;">
                <div class="action-dropdown" style="position: relative; display: inline-block;">
                    <button onclick="toggleStatusActionMenu(${status.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="status_menu_${status.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='viewInspectionStatusDetails(${status.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='editInspectionStatus(${status.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='deleteInspectionStatus(${status.id}, "${status.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>
            .statuses-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
            .action-dropdown button:hover { background: #f0f2f5; }
        </style>
    </div>
    `;

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

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

    // Search
    $('#statusSearch').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 toggleStatusActionMenu(statusId) {
    $('[id^="status_menu_"]').hide();
    $(`#status_menu_${statusId}`).toggle();
}

// ---------- Add Inspection Status ----------
function addInspectionStatus() {
    showInspectionStatusModal('add', null);
}

// Show Add/Edit modal
function showInspectionStatusModal(mode, statusData) {
    const isEdit = mode === 'edit';
    const title = isEdit ? 'Edit Inspection Status' : 'Add New Inspection Status';

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

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

                <!-- Description -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Description <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-align-left" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                        <textarea id="statusDescription" placeholder="Enter description" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;">${isEdit ? statusData.description || '' : ''}</textarea>
                    </div>
                </div>
            </div>

            <style>
                input:focus, textarea: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 Status' : 'Create Status',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '600px',
        preConfirm: () => {
            const code = $('#statusCode').val();
            const name = $('#statusName').val();
            const description = $('#statusDescription').val();

            if (!code) {
                Swal.showValidationMessage('Code is required');
                return false;
            }
            if (!name) {
                Swal.showValidationMessage('Name is required');
                return false;
            }
            if (!description) {
                Swal.showValidationMessage('Description is required');
                return false;
            }

            return {
                code: code.trim(),
                name: name.trim(),
                description: description.trim()
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            if (isEdit) {
                updateInspectionStatus(statusData.id, result.value);
            } else {
                createInspectionStatus(result.value);
            }
        }
    });
}

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

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

    $.ajax({
        url: serverURL + 'inspection-statuses/' + statusId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(status) {
            Swal.close();
            showInspectionStatusModal('edit', status);
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'Could not fetch status details',
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Update inspection status
function updateInspectionStatus(statusId, data) {
    Swal.fire({
        title: 'Updating...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

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

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

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

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