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

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

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

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

    $('#btnAddComplianceRecord').on('click', function () {
        clearComplianceForm();
        $('#document_type_id').val($('#complianceDocumentTypeFilter').val() || '');
        $('#compliance_vehicle_id').val($('#complianceVehicleFilter').val() || '');
        $('#complianceModalTitle').text('Add Renewal');
        showComplianceModal();
    });

    $('#saveComplianceRecord').on('click', saveComplianceRecord);
    $('#btnAddSetupItem').on('click', function () {
        clearSetupForm();
        $('#setupType').val($('#setupTypeFilter').val() || 'states');
        toggleSetupFields();
        showSetupModal();
    });
    $('#saveSetupItem').on('click', saveSetupItem);

    $('#setupTypeFilter').on('change', loadSetupTable);
    $('#setupType').on('change', toggleSetupFields);
    $('#jurisdiction_state').on('change', function () {
        populateLgaSelect('#jurisdiction_lga', $(this).val(), '');
    });
    $('#setupStateId').on('change', function () {
        populateLgaSelect('#setupOfficeLgaId', $(this).val(), '');
    });
    $('#setupOfficeStateId').on('change', function () {
        populateLgaSelect('#setupOfficeLgaId', $(this).val(), '');
    });

    $(document).on('click', '.btn-edit-renewal', function () {
        populateComplianceForm($(this).data('record'));
    });

    $(document).on('click', '.btn-delete-renewal', function () {
        deleteRenewal($(this).data('id'));
    });
});

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');

        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 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 loadDocumentRegistry() {
    $.get('api/compliance.php', { action: 'document_types' }, function (res) {
        if (res.status !== 'success') {
            $('#documentTypeTable').html('<tr><td colspan="5" class="text-center text-muted">Unable to load document registry</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="5" class="text-center text-muted">No registry records found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td><div class="fw-semibold">${escapeHtml(row.name || '-')}</div><div class="text-muted small">${escapeHtml(row.code || '-')}</div></td>
                        <td><div>${escapeHtml(row.issuing_authority || '-')}</div><div class="text-muted small">${escapeHtml(capitalize(row.issuing_level || 'mixed'))}</div></td>
                        <td>${escapeHtml(formatRenewalCycle(row.renewal_cycle_months))}</td>
                        <td>${escapeHtml(buildApplicability(row))}</td>
                        <td>${escapeHtml(row.existing_storage_table || 'Registry only')}</td>
                    </tr>
                `;
            });
        }

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

function loadRenewalHistory() {
    $.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="9" class="text-center text-muted">Unable to load renewal history</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

        if (!rows.length) {
            html = '<tr><td colspan="9" class="text-center text-muted">No renewal history found</td></tr>';
        } else {
            $.each(rows, function (_, row) {
                html += `
                    <tr>
                        <td>${escapeHtml(row.plate_number || '-')}</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>${escapeHtml(formatDate(row.notification_date))}</td>
                        <td>${renderComplianceStatus(row.status_label)}</td>
                        <td>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-sm btn-warning btn-edit-renewal" data-record='${safeJson(row)}'>Edit</button>
                                <button type="button" class="btn btn-sm btn-danger btn-delete-renewal" data-id="${row.id}">Delete</button>
                            </div>
                        </td>
                    </tr>
                `;
            });
        }

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

function loadSetupTable() {
    var setupType = $('#setupTypeFilter').val() || 'states';
    $.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">Unable to load setup items</td></tr>');
            return;
        }

        const rows = res.data || [];
        let html = '';

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

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

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: $('#jurisdiction_state option:selected').text() === 'Select state' ? '' : $('#jurisdiction_state option:selected').text(),
        jurisdiction_lga: $('#jurisdiction_lga option:selected').text() === 'Select LGA' ? '' : $('#jurisdiction_lga option:selected').text(),
        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: $('#issuing_authority_name option:selected').text() === 'Select issuing authority' ? '' : $('#issuing_authority_name option:selected').text(),
        issuing_office: $('#issuing_office option:selected').text() === 'Select issuing office' ? '' : $('#issuing_office option:selected').text(),
        vendor_name: $('#vendor_name option:selected').text() === 'Select vendor / agent' ? '' : $('#vendor_name option:selected').text(),
        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()
    };

    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();
        },
        error: function () {
            showComplianceError('Server error while saving renewal');
        }
    });
}

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) {
        showComplianceError('Setup name is required');
        return;
    }
    if (payload.setup_type === 'lgas' && !payload.state_id) {
        showComplianceError('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') {
                showComplianceError(res.message || 'Unable to save setup item');
                return;
            }

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

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');
    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 },
        success: function (res) {
            if (res.status !== 'success') {
                showComplianceError(res.message || 'Unable to delete renewal');
                return;
            }

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

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 = 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 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 buildJurisdiction(row) {
    const parts = [row.jurisdiction_state, row.jurisdiction_lga].filter(Boolean);
    return parts.length ? parts.join(' / ') : capitalize(row.profile_scope || 'national');
}

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

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 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 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 clearSetupForm() {
    const form = document.getElementById('setupForm');
    if (form) form.reset();
    $('#setupType').val('states');
    toggleSetupFields();
}

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) {
    alert(message);
}

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