$(function () {
    loadIntegrations();
    loadVehicleDropdown();
    $('#searchBox, #statusFilter').on('change', loadIntegrations);
    $('#searchBox').on('input', debounce(loadIntegrations, 300));
    $('#btnAddIntegration').on('click', function () {
        clearForm();
        $('#integrationModalTitle').text('Add Integration');
        $('#integration_id').val(0);
        new bootstrap.Modal(document.getElementById('integrationModal')).show();
    });
    $('#btnSaveIntegration').on('click', saveIntegration);
    $(document).on('click', '.btn-edit-integration', function () {
        var r = _cache.find(function (x) { return String(x.id) === String($(this).data('id')); });
        if (!r) return;
        $('#integration_id').val(r.id);
        $('#integration_name').val(r.name);
        $('#integration_provider').val(r.provider);
        $('#integration_base_url').val(r.base_url||'');
        $('#integration_api_key').val(r.api_key||'');
        $('#integration_api_secret').val(r.api_secret||'');
        $('#integration_auth_type').val(r.auth_type||'header');
        $('#integration_poll_interval').val(r.poll_interval_seconds||300);
        $('#integration_status').val(r.status||'active');
        $('#integration_additional_config').val(r.additional_config||'');
        $('#integrationModalTitle').text('Edit Integration');
        new bootstrap.Modal(document.getElementById('integrationModal')).show();
    });
    $(document).on('click', '.btn-delete-integration', function () {
        if (!confirm('Delete this integration? Device mappings will also be removed.')) return;
        $.post('api/tracker_integrations.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { loadIntegrations(); showAlert('Integration deleted','success'); } else showAlert(r.message,'danger');
        },'json');
    });
    $(document).on('click', '.btn-test-integration', function () {
        var id = $(this).data('id');
        var btn = $(this);
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
        $.post('api/tracker_integrations.php?action=test_connection', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { showAlert(r.message, 'success'); } else { showAlert(r.message, 'danger'); }
            loadIntegrations();
        },'json').always(function () { btn.prop('disabled', false).html('<i class="bi bi-plug"></i>'); });
    });
    $(document).on('click', '.btn-devices-integration', function () {
        var id = $(this).data('id');
        $('#device_integration_id').val(id);
        $('#deviceModalTitle').text('Device Mappings');
        loadDevices(id);
        new bootstrap.Modal(document.getElementById('deviceModal')).show();
    });
    $('#btnFetchDevices').on('click', function () {
        var id = $('#device_integration_id').val();
        if (!id) return;
        var btn = $(this);
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Fetching...');
        $.post('api/tracker_integrations.php?action=fetch_devices', { integration_id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status !== 'success' || !r.data || !r.data.length) {
                deviceAlert((r.message || 'No devices returned from API. You can add devices manually.'), 'warning');
                return;
            }
            var autoAdded = 0;
            r.data.forEach(function (d) {
                var exists = _mappings.some(function (m) { return m.tracker_device_id === String(d.id); });
                if (!exists) {
                    $.post('api/tracker_integrations.php?action=save_mapping', {
                        integration_id: id,
                        tracker_device_id: String(d.id),
                        tracker_device_name: d.name,
                        vehicle_id: '',
                        csrf_token: window.CSRF_TOKEN
                    }, function () {}, 'json');
                    autoAdded++;
                }
            });
            if (autoAdded > 0) {
                deviceAlert('Fetched ' + r.data.length + ' devices, added ' + autoAdded + ' new.', 'success');
                loadDevices(id);
            } else {
                deviceAlert('Fetched ' + r.data.length + ' devices, all already mapped.', 'info');
            }
        },'json').always(function () { btn.prop('disabled', false).html('<i class="bi bi-cloud-download"></i> Fetch from API'); });
    });
    $('#btnAddMapping').on('click', function () {
        $('#mapping_id').val(0);
        $('#mapping_integration_id').val($('#device_integration_id').val());
        $('#mapping_device_id').val('');
        $('#mapping_device_name').val('');
        $('#mapping_vehicle_id').val('');
        $('#mappingModalTitle').text('Add Device Mapping');
        new bootstrap.Modal(document.getElementById('mappingModal')).show();
    });
    $(document).on('click', '.btn-edit-mapping', function () {
        var r = _mappings.find(function (x) { return String(x.id) === String($(this).data('id')); });
        if (!r) return;
        $('#mapping_id').val(r.id);
        $('#mapping_integration_id').val(r.integration_id);
        $('#mapping_device_id').val(r.tracker_device_id);
        $('#mapping_device_name').val(r.tracker_device_name||'');
        $('#mapping_vehicle_id').val(r.vehicle_id||'');
        $('#mappingModalTitle').text('Edit Device Mapping');
        new bootstrap.Modal(document.getElementById('mappingModal')).show();
    });
    $(document).on('click', '.btn-delete-mapping', function () {
        if (!confirm('Delete this device mapping?')) return;
        $.post('api/tracker_integrations.php?action=delete_mapping', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { loadDevices($('#device_integration_id').val()); deviceAlert('Mapping deleted','success'); } else deviceAlert(r.message,'danger');
        },'json');
    });
    $('#btnSaveMapping').on('click', saveMapping);
});

var _cache = [];
var _mappings = [];

function clearForm() {
    $('#integration_id').val(0);
    $('#integration_name, #integration_base_url, #integration_api_key, #integration_api_secret, #integration_additional_config').val('');
    $('#integration_provider').val('generic');
    $('#integration_auth_type').val('header');
    $('#integration_poll_interval').val(300);
    $('#integration_status').val('active');
}

function loadIntegrations() {
    $.get('api/tracker_integrations.php', { action: 'list', search: $('#searchBox').val(), status: $('#statusFilter').val() }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _cache = data;
        var total = data.length, active = 0, inactive = 0, error = 0;
        data.forEach(function (x) {
            if (x.status === 'active') active++;
            else if (x.status === 'inactive') inactive++;
            else error++;
        });
        $('#kpiTotal').text(total);
        $('#kpiActive').text(active);
        $('#kpiInactive').text(inactive);
        $('#kpiError').text(error);
        var html = '';
        if (!data.length) html = '<tr><td colspan="7" class="text-center py-4 text-muted">No integrations</td></tr>';
        else data.forEach(function (x) {
            var statusBadge = x.status === 'active' ? '<span class="badge bg-success">Active</span>'
                : x.status === 'inactive' ? '<span class="badge bg-secondary">Inactive</span>'
                : '<span class="badge bg-danger">Error</span>';
            var lastChecked = x.last_checked_at ? x.last_checked_at : '-';
            var providerLabel = x.provider.charAt(0).toUpperCase() + x.provider.slice(1);
            html += '<tr><td class="fw-semibold">' + esc(x.name) + '</td>'
                + '<td>' + esc(providerLabel) + '</td>'
                + '<td><code>' + esc(x.base_url||'-') + '</code></td>'
                + '<td><span class="badge bg-info bg-opacity-10 text-info">' + (x.device_count||0) + '</span></td>'
                + '<td>' + statusBadge + '</td>'
                + '<td>' + esc(lastChecked) + '</td>'
                + '<td class="text-end">'
                + '<div class="d-flex gap-1 justify-content-end">'
                + '<button class="btn btn-sm btn-outline-success btn-test-integration" data-id="' + x.id + '" title="Test Connection"><i class="bi bi-plug"></i></button>'
                + '<button class="btn btn-sm btn-outline-info btn-devices-integration" data-id="' + x.id + '" title="Manage Devices"><i class="bi bi-hdd-rack"></i></button>'
                + '<button class="btn btn-sm btn-outline-primary btn-edit-integration" data-id="' + x.id + '"><i class="bi bi-pencil"></i></button>'
                + '<button class="btn btn-sm btn-outline-danger btn-delete-integration" data-id="' + x.id + '"><i class="bi bi-trash3"></i></button>'
                + '</div></td></tr>';
        });
        $('#integrationTableBody').html(html);
    },'json');
}

function saveIntegration() {
    var p = {
        id: $('#integration_id').val(),
        name: $('#integration_name').val(),
        provider: $('#integration_provider').val(),
        base_url: $('#integration_base_url').val(),
        api_key: $('#integration_api_key').val(),
        api_secret: $('#integration_api_secret').val(),
        auth_type: $('#integration_auth_type').val(),
        poll_interval_seconds: $('#integration_poll_interval').val(),
        status: $('#integration_status').val(),
        additional_config: $('#integration_additional_config').val(),
        csrf_token: window.CSRF_TOKEN
    };
    if (!p.name) { showAlert('Integration name is required','danger'); return; }
    $.post('api/tracker_integrations.php?action=save', p, function (r) {
        if (r.status !== 'success') { showAlert(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('integrationModal')).hide();
        loadIntegrations();
        showAlert('Integration saved!','success');
    },'json').fail(function(){showAlert('Server error','danger');});
}

function loadDevices(integrationId) {
    $.get('api/tracker_integrations.php', { action: 'list_devices', integration_id: integrationId }, function (r) {
        if (r.status !== 'success') return;
        var data = r.data || []; _mappings = data;
        var html = '';
        if (!data.length) html = '<tr><td colspan="4" class="text-center py-3 text-muted">No device mappings</td></tr>';
        else data.forEach(function (m) {
            var vehicle = m.plate_number ? esc(m.plate_number) : '<span class="text-muted fst-italic">Not mapped</span>';
            html += '<tr><td><code>' + esc(m.tracker_device_id) + '</code></td>'
                + '<td>' + esc(m.tracker_device_name||'-') + '</td>'
                + '<td>' + vehicle + '</td>'
                + '<td class="text-end"><div class="d-flex gap-1 justify-content-end">'
                + '<button class="btn btn-sm btn-outline-primary btn-edit-mapping" data-id="' + m.id + '"><i class="bi bi-pencil"></i></button>'
                + '<button class="btn btn-sm btn-outline-danger btn-delete-mapping" data-id="' + m.id + '"><i class="bi bi-trash3"></i></button>'
                + '</div></td></tr>';
        });
        $('#deviceTableBody').html(html);
    },'json');
}

function loadVehicleDropdown() {
    $.get('api/tracker_integrations.php?action=vehicles', function (r) {
        if (r.status !== 'success') return;
        var html = '<option value="">-- Not mapped --</option>';
        (r.data||[]).forEach(function (v) {
            html += '<option value="' + v.id + '">' + esc(v.plate_number) + (v.vehicle_model ? ' (' + esc(v.vehicle_model) + ')' : '') + '</option>';
        });
        $('#mapping_vehicle_id').html(html);
    },'json');
}

function saveMapping() {
    var p = {
        id: $('#mapping_id').val(),
        integration_id: $('#mapping_integration_id').val(),
        tracker_device_id: $('#mapping_device_id').val(),
        tracker_device_name: $('#mapping_device_name').val(),
        vehicle_id: $('#mapping_vehicle_id').val(),
        csrf_token: window.CSRF_TOKEN
    };
    if (!p.tracker_device_id) { deviceAlert('Tracker device ID is required','danger'); return; }
    if (!p.integration_id) { deviceAlert('Missing integration','danger'); return; }
    $.post('api/tracker_integrations.php?action=save_mapping', p, function (r) {
        if (r.status !== 'success') { deviceAlert(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('mappingModal')).hide();
        loadDevices(p.integration_id);
        deviceAlert('Mapping saved!','success');
    },'json').fail(function(){deviceAlert('Server error','danger');});
}

function showAlert(msg, type) {
    var box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert-' + type).text(msg);
    setTimeout(function(){box.addClass('d-none');},5000);
}

function deviceAlert(msg, type) {
    var box = $('#deviceAlertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert-' + type).text(msg);
    setTimeout(function(){box.addClass('d-none');},5000);
}

function esc(t){return $('<div>').text(t||'').html();}
function debounce(fn,ms){var t;return function(){var c=this,a=arguments;clearTimeout(t);t=setTimeout(function(){fn.apply(c,a);},ms);};}
