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

let _statusFilter = '';

$(function () {
    $.when(loadVehiclesForCompliance(), loadDocumentTypes(), loadSetupOptions()).always(function () {
        loadComplianceSummary();
        loadRenewalHistory();
    });

    $('#complianceVehicleFilter, #complianceDocumentTypeFilter').on('change', function () {
        loadComplianceSummary();
        loadRenewalHistory();
    });

    $('#complianceSearchInput').on('input', debounce(function () {
        loadRenewalHistory();
    }, 300));

    $('#complianceStatusChips').on('click', '.chip-btn', function () {
        const status = $(this).data('status');
        _statusFilter = status;
        $('#complianceStatusChips .chip-btn').removeClass('btn-primary').addClass('btn-outline-secondary');
        $(this).removeClass('btn-outline-secondary').addClass('btn-primary');
        loadRenewalHistory();
    });

    $('#btnRefreshCompliance').on('click', function () {
        loadComplianceSummary();
        loadRenewalHistory();
    });

    $('#btnAddComplianceRecord').on('click', function () {
        clearComplianceForm();
        $('#document_type_id').val($('#complianceDocumentTypeFilter').val() || '');
        $('#compliance_vehicle_id').val($('#complianceVehicleFilter').val() || '');
        $('#complianceModalTitle').text('Add Renewal');
        $('#complianceModalSubtitle').text('Record a new vehicle document renewal');
        showComplianceModal();
    });

    $('#saveComplianceRecord').on('click', saveComplianceRecord);
    $('#jurisdiction_state').on('change', function () {
        populateLgaSelect('#jurisdiction_lga', $(this).val(), '');
    });

    $(document).on('click', '.btn-edit-renewal', function () {
        const id = $(this).data('id');
        const row = _renewalCache.find(r => String(r.id) === String(id));
        if (row) populateComplianceForm(row);
    });

    $(document).on('click', '.btn-delete-renewal', function () {
        deleteRenewal($(this).data('id'));
    });
    $('#btnExportComplianceCsv').on('click', function () { window.location.href = 'api/data_export.php?type=compliance&format=csv'; });
    $('#btnExportComplianceXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=compliance&format=xlsx'; });
    $('#btnExportCompliancePdf').on('click', function () { window.location.href = 'api/data_export.php?type=compliance&format=pdf'; });
});

function loadVehiclesForCompliance() {
    return $.get('api/compliance.php', { action: 'vehicles' }, function (res) {
        if (res.status !== 'success') {
            showComplianceError(res.message || 'Unable to load vehicles');
            return;
        }

        populateSelect('#complianceVehicleFilter', res.data || [], 'All vehicles');
        populateSelect('#compliance_vehicle_id', res.data || [], 'Select vehicle');
    }, 'json');
}

function loadDocumentTypes() {
    return $.get('api/compliance.php', { action: 'document_types' }, function (res) {
        if (res.status !== 'success') {
            showComplianceError(res.message || 'Unable to load document types');
            return;
        }

        populateSelect('#complianceDocumentTypeFilter', res.data || [], 'All document types');
        populateSelect('#document_type_id', res.data || [], 'Select document type');
    }, 'json');
}

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

        complianceSetupCache = res.data || complianceSetupCache;
        populateSelect('#jurisdiction_state', complianceSetupCache.states || [], 'Select state');
        populateSelect('#issuing_authority_name', complianceSetupCache.authorities || [], 'Select issuing authority');
        populateSelect('#issuing_office', complianceSetupCache.offices || [], 'Select issuing office');
        populateSelect('#vendor_name', complianceSetupCache.vendors || [], 'Select vendor / agent');
    }, 'json');
}

function loadComplianceSummary() {
    $.get('api/compliance.php', {
        action: 'summary',
        vehicle_id: $('#complianceVehicleFilter').val(),
        document_type_id: $('#complianceDocumentTypeFilter').val()
    }, function (res) {
        if (res.status !== 'success') {
            showComplianceError(res.message || 'Unable to load compliance summary');
            return;
        }

        const data = res.data || {};
        $('#kpiDocumentTypes').text(data.document_types || 0);
        $('#kpiVehicleProfiles').text(data.vehicle_profiles || 0);
        $('#kpiRenewalRecords').text(data.renewal_records || 0);
        $('#kpiExpiringDocs').text(data.expiring_soon || 0);
    }, 'json');
}

function loadRenewalHistory() {
    const q = $('#complianceSearchInput').val().trim().toLowerCase();

    $.get('api/compliance.php', {
        action: 'renewal_history',
        vehicle_id: $('#complianceVehicleFilter').val(),
        document_type_id: $('#complianceDocumentTypeFilter').val()
    }, function (res) {
        if (res.status !== 'success') {
            $('#renewalHistoryTable').html('<tr><td colspan="8" class="text-center text-muted py-5">Unable to load renewal history</td></tr>');
            $('#renewalCount').text('0 records');
            return;
        }

        let rows = res.data || [];
        _renewalCache = rows;

        if (_statusFilter) {
            rows = rows.filter(function (r) {
                return (r.status_label || '').toLowerCase() === _statusFilter.toLowerCase();
            });
        }

        if (q) {
            rows = rows.filter(function (r) {
                return (r.plate_number || '').toLowerCase().indexOf(q) !== -1
                    || (r.document_name || '').toLowerCase().indexOf(q) !== -1
                    || (r.document_code || '').toLowerCase().indexOf(q) !== -1
                    || (r.document_number || '').toLowerCase().indexOf(q) !== -1
                    || (r.jurisdiction_state || '').toLowerCase().indexOf(q) !== -1;
            });
        }

        $('#renewalCount').text(rows.length + ' record' + (rows.length !== 1 ? 's' : ''));
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="8" class="text-center text-muted py-5">No renewal history found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td><div class="fw-semibold">${escapeHtml(row.plate_number || '-')}</div></td>
                        <td>
                            <div class="fw-semibold">${escapeHtml(row.document_name || '-')}</div>
                            <div class="text-muted small">${escapeHtml(row.document_code || '-')}</div>
                        </td>
                        <td>${escapeHtml(buildJurisdiction(row))}</td>
                        <td>${escapeHtml(row.document_number || '-')}</td>
                        <td>${escapeHtml(formatDate(row.issue_date))}</td>
                        <td>${escapeHtml(formatDate(row.expiry_date))}</td>
                        <td>${renderComplianceStatus(row.status_label)}</td>
                        <td class="text-end">
                            <div class="d-flex gap-1 justify-content-end">
                                <button type="button" class="btn btn-sm btn-outline-secondary btn-edit-renewal" title="Edit" data-id="${row.id}"><i class="bi bi-pencil"></i></button>
                                <button type="button" class="btn btn-sm btn-outline-danger btn-delete-renewal" title="Delete" data-id="${row.id}"><i class="bi bi-trash3"></i></button>
                            </div>
                        </td>
                    </tr>
                `;
            });
        }

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

function selectedText(sel) {
    const $o = $(sel + ' option:selected');
    return $o.length && $o.val() ? $o.text() : '';
}

function saveComplianceRecord() {
    const payload = {
        id: $('#compliance_id').val(),
        vehicle_id: $('#compliance_vehicle_id').val(),
        document_type_id: $('#document_type_id').val(),
        profile_scope: $('#profile_scope').val(),
        jurisdiction_state: selectedText('#jurisdiction_state'),
        jurisdiction_lga: selectedText('#jurisdiction_lga'),
        document_number: $('#document_number').val().trim(),
        issue_date: $('#issue_date').val(),
        expiry_date: $('#expiry_date').val(),
        notification_date: $('#notification_date').val(),
        status: $('#renewal_status').val(),
        is_mandatory: $('#is_mandatory').val(),
        issuing_authority_name: selectedText('#issuing_authority_name'),
        issuing_office: selectedText('#issuing_office'),
        vendor_name: selectedText('#vendor_name'),
        amount_paid: $('#amount_paid').val(),
        payment_reference: $('#payment_reference').val().trim(),
        receipt_number: $('#receipt_number').val().trim(),
        file_url: $('#file_url').val().trim(),
        profile_remarks: $('#profile_remarks').val().trim(),
        renewal_notes: $('#renewal_notes').val().trim(),
        csrf_token: window.CSRF_TOKEN
    };

    if (!payload.vehicle_id) {
        showComplianceError('Vehicle is required');
        return;
    }
    if (!payload.document_type_id) {
        showComplianceError('Document type is required');
        return;
    }
    if (!payload.expiry_date) {
        showComplianceError('Expiry date is required');
        return;
    }

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

            hideComplianceModal();
            loadComplianceSummary();
            loadRenewalHistory();
            showComplianceSuccess('Renewal saved!');
        },
        error: function () {
            showComplianceError('Server error while saving renewal');
        }
    });
}

function populateComplianceForm(record) {
    clearComplianceForm();

    $('#compliance_id').val(record.id || '');
    $('#compliance_vehicle_id').val(record.vehicle_id || '');
    $('#document_type_id').val(record.document_type_id || '');
    $('#profile_scope').val(record.profile_scope || 'national');

    const stateOption = findOptionByText(complianceSetupCache.states, record.jurisdiction_state);
    $('#jurisdiction_state').val(stateOption ? String(stateOption.id) : '');
    populateLgaSelect('#jurisdiction_lga', $('#jurisdiction_state').val(), record.jurisdiction_lga || '');

    $('#document_number').val(record.document_number || '');
    $('#issue_date').val(normalizeDateInput(record.issue_date));
    $('#expiry_date').val(normalizeDateInput(record.expiry_date));
    $('#notification_date').val(normalizeDateInput(record.notification_date));
    $('#renewal_status').val(record.status || 'valid');
    $('#is_mandatory').val(String(Number(record.is_mandatory || 1)));

    const authorityOption = findOptionByText(complianceSetupCache.authorities, record.issuing_authority_name);
    const officeOption = findOptionByText(complianceSetupCache.offices, record.issuing_office);
    const vendorOption = findOptionByText(complianceSetupCache.vendors, record.vendor_name);
    $('#issuing_authority_name').val(authorityOption ? String(authorityOption.id) : '');
    $('#issuing_office').val(officeOption ? String(officeOption.id) : '');
    $('#vendor_name').val(vendorOption ? String(vendorOption.id) : '');

    $('#amount_paid').val(record.amount_paid || '');
    $('#payment_reference').val(record.payment_reference || '');
    $('#receipt_number').val(record.receipt_number || '');
    $('#file_url').val(record.file_url || '');
    $('#profile_remarks').val(record.profile_remarks || '');
    $('#renewal_notes').val(record.renewal_notes || '');

    $('#complianceModalTitle').text('Edit Renewal');
    $('#complianceModalSubtitle').text('Update vehicle document renewal details');
    showComplianceModal();
}

function deleteRenewal(id) {
    if (!id || !confirm('Delete this renewal record?')) {
        return;
    }

    $.ajax({
        url: 'api/compliance.php?action=delete_renewal',
        method: 'POST',
        dataType: 'json',
        data: { id: id, csrf_token: window.CSRF_TOKEN },
        success: function (res) {
            if (res.status !== 'success') {
                showComplianceError(res.message || 'Unable to delete renewal');
                return;
            }

            loadComplianceSummary();
            loadRenewalHistory();
            showComplianceSuccess('Renewal deleted');
        },
        error: function () {
            showComplianceError('Server error while deleting renewal');
        }
    });
}

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 = findOptionByText(rows, selectedName);
        if (option) {
            $(selector).val(String(option.id));
        }
    }
}

function findOptionByText(rows, text) {
    if (!text) {
        return null;
    }
    return (rows || []).find(function (row) {
        return String(row.label || row.name || '').toLowerCase() === String(text).toLowerCase();
    }) || null;
}

function buildJurisdiction(row) {
    const parts = [row.jurisdiction_state, row.jurisdiction_lga].filter(Boolean);
    return parts.length ? parts.join(' / ') : capitalize(row.profile_scope || 'national');
}

function renderComplianceStatus(status) {
    const normalized = (status || '').toLowerCase();

    if (normalized === 'expired') return '<span class="badge bg-danger">Expired</span>';
    if (normalized === 'expiring soon') return '<span class="badge bg-warning text-dark">Expiring Soon</span>';
    if (normalized === 'draft') return '<span class="badge bg-secondary">Draft</span>';
    if (normalized === 'revoked') return '<span class="badge bg-dark">Revoked</span>';
    if (normalized === 'waived') return '<span class="badge bg-info text-dark">Waived</span>';

    return '<span class="badge bg-success">Valid</span>';
}

function showComplianceModal() {
    new bootstrap.Modal(document.getElementById('complianceModal')).show();
}

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

function clearComplianceForm() {
    const form = document.getElementById('complianceForm');
    if (form) form.reset();

    $('#compliance_id').val('');
    $('#profile_scope').val('national');
    $('#renewal_status').val('valid');
    $('#is_mandatory').val('1');
    $('#jurisdiction_lga').html('<option value="">Select LGA</option>');
}

function normalizeDateInput(value) {
    if (!value) return '';
    return String(value).slice(0, 10);
}

function formatDate(value) {
    if (!value) return '-';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return value;
    return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}

function capitalize(text) {
    const value = String(text || '');
    return value ? value.charAt(0).toUpperCase() + value.slice(1) : '-';
}

function safeJson(value) {
    return escapeHtml(JSON.stringify(value));
}

function showComplianceError(message) {
    showComplianceToast(message, 'danger');
}

function showComplianceSuccess(message) {
    showComplianceToast(message, 'success');
}

function showComplianceToast(msg, type) {
    const el = document.createElement('div');
    el.className = 'position-fixed top-0 end-0 p-3';
    el.style.cssText = 'z-index:9999';
    el.innerHTML = '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
        escapeHtml(msg) + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 5000);
}

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

function debounce(fn, ms) {
    let timer;
    return function () {
        var ctx = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () { fn.apply(ctx, args); }, ms);
    };
}
