let complianceSetupCache = {
    states: [],
    lgas: [],
    authorities: [],
    offices: [],
    vendors: []
};
let currentSetupType = 'states';

$(function () {
    loadSetupOptions().always(function () {
        loadDocumentRegistry();
        currentSetupType = 'regions';
        loadSetupTable();
        updateCategoryButtons('regions');
    });

    $('#setupTypeFilter').on('change', function () {
        currentSetupType = $(this).val() || 'regions';
        updateCategoryButtons(currentSetupType);
        loadSetupTable();
    });
    $('#setupSearch').on('keyup', function () {
        clearTimeout(this._searchTimer);
        const search = $(this).val();
        this._searchTimer = setTimeout(function () {
            loadSetupTable();
        }, 300);
    });
    $('#registrySearch').on('keyup', function () {
        clearTimeout(this._searchTimer);
        const search = $(this).val();
        this._searchTimer = setTimeout(function () {
            loadDocumentRegistry();
        }, 300);
    });
    $(document).on('click', '.setup-category-btn', function () {
        const category = $(this).data('setup-category');
        if (!category) return;

        currentSetupType = category;
        $('#setupTypeFilter').val(category);
        updateCategoryButtons(category);
        loadSetupTable(category);

        clearSetupForm();
        $('#setupType').val(category);
        toggleSetupFields();
        showSetupModal();
    });
    $('#btnAddSetupItem').on('click', function () {
        clearSetupForm();
        $('#setupType').val(currentSetupType);
        toggleSetupFields();
        showSetupModal();
    });
    $('#setupType').on('change', toggleSetupFields);
    $('#saveSetupItem').on('click', saveSetupItem);

    // Document Type Modal handlers
    $('#btnAddDocumentType').on('click', function () {
        clearDocumentTypeForm();
        showDocumentTypeModal();
    });

    $(document).on('click', '.registry-card', function () {
        const docId = $(this).data('doc-id');
        const docData = {
            id: docId,
            name: $(this).data('doc-name'),
            code: $(this).data('doc-code'),
            issuing_authority: $(this).data('doc-issuer'),
            renewal_cycle_months: $(this).data('doc-renewal'),
            required_for_private: $(this).data('doc-private'),
            required_for_commercial: $(this).data('doc-commercial'),
            required_for_heavy_duty: $(this).data('doc-heavy'),
            required_for_interstate: $(this).data('doc-interstate'),
            existing_storage_table: $(this).data('doc-storage')
        };
        loadDocumentTypeIntoForm(docData);
        showDocumentTypeModal();
    });

    $('#saveDocumentType').on('click', saveDocumentType);

    $('#setupOfficeStateId').on('change', function () {
        populateLgaSelect('#setupOfficeLgaId', $(this).val(), '');
    });
});

function loadDocumentRegistry() {
    const search = $('#registrySearch').val().trim().toLowerCase();

    $.get('api/compliance.php', { action: 'document_types' }, function (res) {
        if (res.status !== 'success') {
            $('#documentTypeGrid').html('<div class="col-12"><div class="text-center text-muted py-4">Unable to load document registry</div></div>');
            return;
        }

        let allRows = res.data || [];
        let rows = allRows;
        if (search) {
            rows = rows.filter(function (row) {
                const text = `${row.name || ''} ${row.code || ''} ${row.issuing_authority || ''}`.toLowerCase();
                return text.indexOf(search) !== -1;
            });
        }

        $('#kpiDocumentTypes').text(allRows.length);
        $('#registryCount').text(rows.length);

        let html = '';
        if (!rows.length) {
            html = '<div class="col-12"><div class="text-center text-muted py-4">No registry records found</div></div>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <div class="col-12 col-md-6 col-xl-12">
                        <div class="card registry-card border-0 bg-light h-100 cursor-pointer" 
                            data-doc-id="${row.id}"
                            data-doc-name="${escapeHtml(row.name || '')}"
                            data-doc-code="${escapeHtml(row.code || '')}"
                            data-doc-issuer="${escapeHtml(row.issuing_authority || '')}"
                            data-doc-renewal="${row.renewal_cycle_months || ''}"
                            data-doc-private="${row.required_for_private || 0}"
                            data-doc-commercial="${row.required_for_commercial || 0}"
                            data-doc-heavy="${row.required_for_heavy_duty || 0}"
                            data-doc-interstate="${row.required_for_interstate || 0}"
                            data-doc-storage="${escapeHtml(row.existing_storage_table || '')}"
                            style="cursor: pointer;">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                                    <div>
                                        <div class="fw-semibold">${escapeHtml(row.name || '-')}</div>
                                        <div class="text-muted small">${escapeHtml(row.code || '-')}</div>
                                    </div>
                                    <div class="icon-wrap"><i class="bi bi-file-earmark-check"></i></div>
                                </div>
                                <div class="small text-muted mb-1">Authority</div>
                                <div class="mb-2">${escapeHtml(row.issuing_authority || '-')}</div>
                                <div class="small text-muted mb-1">Renewal Cycle</div>
                                <div class="mb-2">${escapeHtml(formatRenewalCycle(row.renewal_cycle_months))}</div>
                                <div class="small text-muted mb-1">Applicability</div>
                                <div class="mb-2">${escapeHtml(buildApplicability(row))}</div>
                                <div class="small text-muted mb-1">Storage</div>
                                <div>${escapeHtml(row.existing_storage_table || 'Registry only')}</div>
                            </div>
                        </div>
                    </div>
                `;
            });
        }

        $('#documentTypeGrid').html(html);
    }, 'json');
}

function updateCategoryButtons(selectedCategory) {
    $('.setup-category-btn').each(function () {
        const category = $(this).data('setup-category');
        $(this).toggleClass('active', category === selectedCategory);
    });
}

function loadSetupOptions() {
    return $.get('api/compliance.php', { action: 'setup_options' }, function (res) {
        if (res.status !== 'success') {
            alert(res.message || 'Unable to load setup options');
            return;
        }

        complianceSetupCache = res.data || complianceSetupCache;
        populateSelect('#setupStateId', complianceSetupCache.states || [], 'Select state');
        populateSelect('#setupOfficeStateId', complianceSetupCache.states || [], 'Select state');
        populateSelect('#setupAuthorityId', complianceSetupCache.authorities || [], 'Select issuing authority');
        populateSelect('#setupOfficeLgaId', complianceSetupCache.lgas || [], 'Select LGA');
    }, 'json');
}

function loadSetupTable(setupType) {
    const search = $('#setupSearch').val().trim().toLowerCase();

    if (setupType) currentSetupType = setupType;
    else setupType = currentSetupType;
    $.get('api/compliance.php', { action: 'setup_list', setup_type: setupType }, function (res) {
        if (res.status !== 'success') {
            $('#setupTable').html('<tr><td colspan="3" class="text-center text-muted">' + escapeHtml(res.message || 'Unable to load setup items') + '</td></tr>');
            $('#kpiActiveSetup').text(0);
            $('#kpiInactiveSetup').text(0);
            return;
        }

        let rows = res.data || [];
        if (search) {
            rows = rows.filter(function (row) {
                const text = `${row.name || ''} ${row.context || ''}`.toLowerCase();
                return text.indexOf(search) !== -1;
            });
        }

        let html = '';
        let activeCount = 0;
        let inactiveCount = 0;

        if (!rows.length) {
            html = '<tr><td colspan="3" class="text-center text-muted">No setup items found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                const active = Number(row.is_active || 0) === 1;
                if (active) {
                    activeCount++;
                } else {
                    inactiveCount++;
                }
                html += `
                    <tr>
                        <td>${escapeHtml(row.name || '-')}</td>
                        <td>${escapeHtml(row.context || '-')}</td>
                        <td>${active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'}</td>
                    </tr>
                `;
            });
        }

        $('#setupTable').html(html);
        $('#kpiActiveSetup').text(activeCount);
        $('#kpiInactiveSetup').text(inactiveCount);
    }, 'json').fail(function (jqXHR) {
        $('#setupTable').html('<tr><td colspan="3" class="text-center text-muted">Request failed: ' + escapeHtml(jqXHR.status + ' ' + jqXHR.statusText) + '</td></tr>');
    });
}

function saveSetupItem() {
    const payload = {
        setup_type: $('#setupType').val(),
        name: $('#setupName').val().trim(),
        code: $('#setupCode').val().trim(),
        state_id: $('#setupStateId').val(),
        authority_level: $('#setupAuthorityLevel').val(),
        authority_id: $('#setupAuthorityId').val(),
        office_state_id: $('#setupOfficeStateId').val(),
        office_lga_id: $('#setupOfficeLgaId').val(),
        vendor_type: $('#setupVendorType').val(),
        phone: $('#setupPhone').val().trim()
    };

    if (!payload.name) {
        alert('Setup name is required');
        return;
    }
    if (payload.setup_type === 'lgas' && !payload.state_id) {
        alert('State is required for LGA setup');
        return;
    }

    $.ajax({
        url: 'api/compliance.php?action=save_setup_item',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') {
                alert(res.message || 'Unable to save setup item');
                return;
            }

            hideSetupModal();
            loadSetupOptions().always(function () {
                loadDocumentRegistry();
                loadSetupTable();
            });
        },
        error: function () {
            alert('Server error while saving setup item');
        }
    });
}

function toggleSetupFields() {
    const type = $('#setupType').val();

    $('.setup-state-code').toggleClass('d-none', type !== 'states');
    $('.setup-lga-state').toggleClass('d-none', type !== 'lgas');
    $('.setup-authority-level').toggleClass('d-none', type !== 'authorities');
    $('.setup-office-authority').toggleClass('d-none', type !== 'offices');
    $('.setup-office-state').toggleClass('d-none', type !== 'offices');
    $('.setup-office-lga').toggleClass('d-none', type !== 'offices');
    $('.setup-vendor-type').toggleClass('d-none', type !== 'vendors');
    $('.setup-vendor-phone').toggleClass('d-none', type !== 'vendors');
}

function populateSelect(selector, rows, placeholder) {
    const currentValue = $(selector).val();
    let html = `<option value="">${escapeHtml(placeholder)}</option>`;

    $.each(rows, function (_, row) {
        html += `<option value="${escapeHtml(row.id)}">${escapeHtml(row.label || row.name || '-')}</option>`;
    });

    $(selector).html(html);
    if (currentValue) {
        $(selector).val(String(currentValue));
    }
}

function populateLgaSelect(selector, stateId, selectedName) {
    let rows = complianceSetupCache.lgas || [];
    if (stateId) {
        rows = rows.filter(function (row) {
            return String(row.state_id) === String(stateId);
        });
    }

    populateSelect(selector, rows, 'Select LGA');
    if (selectedName) {
        const option = rows.find(function (row) {
            return String(row.label || '').toLowerCase() === String(selectedName).toLowerCase();
        });
        if (option) {
            $(selector).val(String(option.id));
        }
    }
}

function showSetupModal() {
    new bootstrap.Modal(document.getElementById('setupModal')).show();
}

function hideSetupModal() {
    const modalEl = document.getElementById('setupModal');
    const instance = bootstrap.Modal.getInstance(modalEl);
    if (instance) instance.hide();
}

function clearSetupForm() {
    const form = document.getElementById('setupForm');
    if (form) form.reset();
    $('#setupType').val('states');
    toggleSetupFields();
}

// Document Type Modal Handlers
function showDocumentTypeModal() {
    new bootstrap.Modal(document.getElementById('documentTypeModal')).show();
}

function hideDocumentTypeModal() {
    const modalEl = document.getElementById('documentTypeModal');
    const instance = bootstrap.Modal.getInstance(modalEl);
    if (instance) instance.hide();
}

function clearDocumentTypeForm() {
    const form = document.getElementById('documentTypeForm');
    if (form) form.reset();
    $('#docTypeId').val('');
    $('#docTypeModalTitle').text('Add Document Type');
}

function loadDocumentTypeIntoForm(docData) {
    $('#docTypeId').val(docData.id || '');
    $('#docTypeName').val(docData.name || '');
    $('#docTypeCode').val(docData.code || '');
    $('#docTypeIssuer').val(docData.issuing_authority || '');
    $('#docTypeRenewalMonths').val(docData.renewal_cycle_months || '');
    $('#docTypeStorageTable').val(docData.existing_storage_table || '');
    
    // Set checkboxes based on applicability flags
    $('#docTypePrivate').prop('checked', Number(docData.required_for_private) === 1);
    $('#docTypeCommercial').prop('checked', Number(docData.required_for_commercial) === 1);
    $('#docTypeHeavyDuty').prop('checked', Number(docData.required_for_heavy_duty) === 1);
    $('#docTypeInterstate').prop('checked', Number(docData.required_for_interstate) === 1);
    
    $('#docTypeModalTitle').text('Edit Document Type');
}

function saveDocumentType() {
    const payload = {
        id: $('#docTypeId').val() || null,
        name: $('#docTypeName').val().trim(),
        code: $('#docTypeCode').val().trim(),
        issuing_authority: $('#docTypeIssuer').val().trim(),
        renewal_cycle_months: $('#docTypeRenewalMonths').val() || 0,
        required_for_private: $('#docTypePrivate').is(':checked') ? 1 : 0,
        required_for_commercial: $('#docTypeCommercial').is(':checked') ? 1 : 0,
        required_for_heavy_duty: $('#docTypeHeavyDuty').is(':checked') ? 1 : 0,
        required_for_interstate: $('#docTypeInterstate').is(':checked') ? 1 : 0,
        existing_storage_table: $('#docTypeStorageTable').val().trim()
    };

    if (!payload.name) {
        alert('Document type name is required');
        return;
    }

    $.ajax({
        url: 'api/compliance.php?action=save_document_type',
        method: 'POST',
        dataType: 'json',
        data: payload,
        success: function (res) {
            if (res.status !== 'success') {
                alert(res.message || 'Unable to save document type');
                return;
            }

            hideDocumentTypeModal();
            loadDocumentRegistry();
        },
        error: function () {
            alert('Server error while saving document type');
        }
    });
}

function buildApplicability(row) {
    const parts = [];
    if (Number(row.required_for_private) === 1) parts.push('Private');
    if (Number(row.required_for_commercial) === 1) parts.push('Commercial');
    if (Number(row.required_for_heavy_duty) === 1) parts.push('Heavy Duty');
    if (Number(row.required_for_interstate) === 1) parts.push('Interstate');
    return parts.length ? parts.join(', ') : 'Optional / situational';
}

function formatRenewalCycle(months) {
    if (!months || Number(months) <= 0) {
        return 'Non-renewing / manual';
    }
    if (Number(months) === 12) {
        return 'Yearly';
    }
    return `${months} months`;
}

function escapeHtml(text) {
    return $('<div>').text(text || '').html();
}
