window.currentIcdPage = 1;
window.icdSearchTimeout = null;

window.debounceFetchIcd = function() {
    clearTimeout(window.icdSearchTimeout);
    window.icdSearchTimeout = setTimeout(() => {
        window.fetchIcdDictionary(1);
    }, 400); 
};

window.fetchIcdDictionary = function(page = 1) {
    window.currentIcdPage = page;
    const tbody = document.getElementById('icdTableBody');
    if(!tbody) return;

    const search = document.getElementById('icdSearch') ? document.getElementById('icdSearch').value : '';
    const limit = document.getElementById('icdLimit') ? document.getElementById('icdLimit').value : 50;

    tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding: 40px; color:#64748b;"><i class="fa-solid fa-spinner fa-spin" style="font-size: 24px; margin-bottom:10px;"></i><br>Fetching Dictionary Data...</td></tr>`;

    fetch(`../../dripend/systemSetup/gdrg/fetch_icd10.php?page=${page}&limit=${limit}&search=${encodeURIComponent(search)}`)
        .then(async response => {
            const text = await response.text(); 
            try {
                const data = JSON.parse(text);
                if (data.error) {
                    tbody.innerHTML = `<tr><td colspan="5" style="padding: 20px; color:#dc2626; background:#fef2f2;"><strong>Database Error:</strong><br>${data.error}</td></tr>`;
                    return;
                }
                window.renderIcdTable(data);
            } catch (e) {
                console.error("Parse Error:", e);
                tbody.innerHTML = `<tr><td colspan="5" style="padding: 20px; color:#dc2626; background:#fef2f2;"><strong>Server Error:</strong><br><textarea style="width:100%; height:100px;">${text}</textarea></td></tr>`;
            }
        })
        .catch(err => {
            console.error('Fetch Error:', err);
            tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding: 40px; color:#dc2626;"><i class="fa-solid fa-wifi" style="font-size: 24px; margin-bottom:10px;"></i><br>Network Error. Cannot reach the server.</td></tr>`;
        });
};

window.renderIcdTable = function(data) {
    const tbody = document.getElementById('icdTableBody');
    
    if (!data.records || data.records.length === 0) {
        tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; padding: 40px; color:#64748b;">No ICD-10 codes found matching your search.</td></tr>`;
        window.updateIcdPagination(0, 0, 0, 0);
        return;
    }

    tbody.innerHTML = ''; 
    let globalIndex = ((data.current_page - 1) * data.limit) + 1;

    data.records.forEach(item => {
        // Safe check for is_active. Defaults to 1 if you haven't added the column yet.
        const isActive = item.is_active !== undefined ? item.is_active : 1;
        const activeClass = isActive == 1 ? 'active' : 'inactive';
        
        const statusBadge = isActive == 1 
            ? `<span style="background:#dcfce7; color:#16a34a; padding:4px 8px; border-radius:6px; font-size:11px; font-weight:700; border:1px solid #bbf7d0;">Active</span>` 
            : `<span style="background:#f1f5f9; color:#64748b; padding:4px 8px; border-radius:6px; font-size:11px; font-weight:700; border:1px solid #e2e8f0;">Inactive</span>`;

        // SPA-Safe Action Buttons routing to respective pages
        const actionButtons = `
            <div class="actions-flex">
                <button class="btn-action view" title="View Code" onclick="if(typeof loadContent === 'function') { loadContent('View ICD-10', 'gdrg/viewIcd.php?code=${item.code}', 'ICD-10 Dictionary', 'facility', null, true); }"><i class="fa-solid fa-eye"></i></button>
                <button class="btn-action edit" title="Edit Code" onclick="if(typeof loadContent === 'function') { loadContent('Edit ICD-10', 'gdrg/editIcd.php?code=${item.code}', 'ICD-10 Dictionary', 'facility', null, true); }"><i class="fa-solid fa-pen"></i></button>
                <button class="btn-action toggle ${activeClass}" title="${isActive == 1 ? 'Deactivate' : 'Activate'}" onclick="if(typeof loadContent === 'function') { loadContent('Toggle Status', 'gdrg/toggleIcd.php?code=${item.code}', 'ICD-10 Dictionary', 'facility', null, true); }"><i class="fa-solid fa-power-off"></i></button>
                <button class="btn-action delete" title="Delete Code" onclick="if(confirm('Are you sure you want to completely delete code ${item.code}?')) { if(typeof loadContent === 'function') { loadContent('Delete ICD', 'gdrg/deleteIcd.php?code=${item.code}', 'ICD-10 Dictionary', 'facility', null, true); } }"><i class="fa-solid fa-trash"></i></button>
            </div>
        `;

        tbody.insertAdjacentHTML('beforeend', `
            <tr style="opacity: ${isActive == 1 ? '1' : '0.6'};">
                <td style="font-weight:600; color:#94a3b8;">${globalIndex}</td>
                <td><span class="code-badge">${item.code}</span></td>
                <td><span class="desc-text">${item.description}</span></td>
                <td>${statusBadge}</td>
                <td>${actionButtons}</td>
            </tr>
        `);
        globalIndex++;
    });

    window.updateIcdPagination(data.total_records, data.total_pages, window.currentIcdPage, data.limit);
};

window.updateIcdPagination = function(totalRecords, totalPages, current, limit) {
    const prevBtn = document.getElementById('icdPrev');
    const nextBtn = document.getElementById('icdNext');
    const pageInfo = document.getElementById('icdPageInfo');

    if(prevBtn) prevBtn.disabled = current <= 1;
    if(nextBtn) nextBtn.disabled = current >= totalPages || totalPages === 0;

    if(pageInfo) {
        if (totalRecords === 0) {
            pageInfo.textContent = `Showing 0 entries`;
        } else {
            const start = ((current - 1) * limit) + 1;
            const end = Math.min(current * limit, totalRecords);
            pageInfo.textContent = `Showing ${start} to ${end} of ${totalRecords} entries (Page ${current} of ${totalPages})`;
        }
    }
};

window.changeIcdPage = function(direction) {
    window.fetchIcdDictionary(window.currentIcdPage + direction);
};