var _pageState = { page: 1, search: '', status: '' };

$(document).ready(function () {
    loadReferenceOptions().always(function () {
        loadVehicles();
    });

    $('#btnAddVehicle').on('click', function () {
        clearVehicleForm();
        $('#modalTitle').text('Add Vehicle');
        showVehicleModal();
    });

    $('#btnRefresh').on('click', function () {
        _pageState.page = 1;
        loadVehicles();
    });

    $('#btnExport').on('click', function () {
        var params = $.param({ action: 'list', search: _pageState.search, status: _pageState.status, page: 1, per_page: 10000 });
        window.open('api/vehicles.php?' + params + '&export=csv', '_blank');
    });

    var typingTimer;
    $('#searchVehicle').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () {
            _pageState.page = 1;
            _pageState.search = $('#searchVehicle').val();
            loadVehicles();
        }, 350);
    });

    $('#statusFilter').on('change', function () {
        _pageState.page = 1;
        _pageState.status = $(this).val();
        loadVehicles();
    });

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

    $(document).on('click', '.btn-edit-vehicle', function () {
        const vehicle = $(this).data('vehicle');
        editVehicle(vehicle);
    });

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

    $(document).on('click', '.btn-view-vehicle', function () {
        const id = $(this).data('id');
        if (id) {
            window.location.href = 'vehicle_profile.php?id=' + id;
        }
    });

    $(document).on('click', '.page-link', function () {
        var p = parseInt($(this).data('page'), 10);
        if (p > 0 && p !== _pageState.page) {
            _pageState.page = p;
            loadVehicles();
        }
    });
});

function loadReferenceOptions() {
    return $.ajax({
        url: 'api/vehicles.php',
        method: 'GET',
        dataType: 'json',
        data: { action: 'reference_options' },
        success: function (res) {
            if (res.status !== 'success') {
                showVehicleError(res.message || 'Unable to load reference options');
                return;
            }

            populateSelect('#supplier_id', res.data.suppliers || [], 'Select supplier');
            populateSelect('#contract_id', res.data.contracts || [], 'Select contract');
            populateSelect('#country_id', res.data.countries || [], 'Select country');
            populateSelect('#city_id', res.data.cities || [], 'Select city');
            populateSelect('#region_id', res.data.regions || [], 'Select region');
            populateSelect('#department_id', res.data.departments || [], 'Select department');
            populateSelect('#project_id', res.data.projects || [], 'Select project');
            populateSelect('#office_id', res.data.offices || [], 'Select office');
            populateSelect('#location_id', res.data.locations || [], 'Select location');
            populateSelect('#schedule_id', res.data.schedules || [], 'Select schedule');
            populateSelect('#vehicle_owner', res.data.owners || [], 'Select Owner', 'label');
            populateSelect('#vehicle_model', res.data.vehicle_models || [], 'Select Model', 'label');
            populateSelect('#vehicle_type', res.data.vehicle_types || [], 'Select Type', 'label');
            populateSelect('#vehicle_use_type', res.data.vehicle_use_types || [], 'Select Use Type');
        },
        error: function () {
            showVehicleError('Server error while loading reference options');
        }
    });
}

function loadVehicles() {
    $('#vehicleTable').html('<tr><td colspan="5" class="text-center text-muted">Loading vehicles...</td></tr>');

    $.ajax({
        url: 'api/vehicles.php',
        method: 'GET',
        dataType: 'json',
        data: { action: 'list', search: _pageState.search, status: _pageState.status, page: _pageState.page, per_page: 50 },
        success: function (res) {
            if (res.status !== 'success') {
                showVehicleError(res.message || 'Failed to load vehicles');
                return;
            }

            renderVehicleKpis(res.meta || {});
            renderVehicleTable(res.data || []);
            renderPagination(res.meta || {});
        },
        error: function () {
            showVehicleError('Server error while loading vehicles');
        }
    });
}

function renderVehicleKpis(meta) {
    $('#kpiVehiclesTotal').text(meta.total || 0);
    $('#kpiVehiclesActive').text(meta.active || 0);
    $('#kpiVehiclesWorkshop').text(meta.workshop || 0);
    $('#kpiVehiclesInactive').text(meta.inactive || 0);
}

function renderVehicleTable(vehicles) {
    if (!vehicles.length) {
        $('#vehicleTable').html(`
            <tr>
                <td colspan="5" class="text-center text-muted">No vehicles found</td>
            </tr>
        `);
        return;
    }

    let html = '';

    $.each(vehicles, function (_, vehicle) {
        const vehicleName = [vehicle.vehicle_model, vehicle.vehicle_type]
            .filter(Boolean)
            .join(' ');
        const classification = [vehicle.owner, vehicle.vehicle_use_type].filter(Boolean).join(' • ');

        html += `
            <tr>
                <td>
                    <div class="fw-semibold">${escapeHtml(vehicle.plate_number)}</div>
                    <div class="text-muted small">${escapeHtml(vehicleName || 'No model details')}</div>
                </td>
                <td>
                    <div>${escapeHtml(classification || vehicle.vehicle_type || 'Unspecified')}</div>
                    <div class="text-muted small">${escapeHtml(vehicle.property || vehicle.vehicle_source || 'No extra classification')}</div>
                </td>
                <td>${escapeHtml(vehicle.year_of_manufacturing || '-')}</td>
                <td>${renderVehicleStatus(vehicle.vehicle_status)}</td>
                <td>
                    <div class="d-flex flex-wrap gap-2">
                        <button type="button" class="btn btn-sm btn-info btn-view-vehicle" data-id="${vehicle.id}">
                            View
                        </button>
                        <button type="button" class="btn btn-sm btn-warning btn-edit-vehicle" data-vehicle='${safeJson(vehicle)}'>
                            Edit
                        </button>
                        <button type="button" class="btn btn-sm btn-danger btn-delete-vehicle" data-id="${vehicle.id}">
                            Delete
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });

    $('#vehicleTable').html(html);
}

function saveVehicle() {
    const data = {
        id: $('#vehicle_id').val(),
        plate_number: $('#plate_number').val().trim(),
        vehicle_model: $('#vehicle_model').val().trim(),
        owner: $('#vehicle_owner').val().trim(),
        property: $('#vehicle_property').val().trim(),
        vehicle_type: $('#vehicle_type').val().trim(),
        year: $('#year_of_manufacturing').val(),
        status: $('#vehicle_status').val()
        ,
        vehicle_use_type: $('#vehicle_use_type').val().trim(),
        vehicle_source: $('#vehicle_source').val().trim(),
        displacement: $('#vehicle_displacement').val().trim(),
        seats: $('#vehicle_seats').val(),
        standard_fuel_consumption_l_per_100km: $('#standard_fuel_consumption').val(),
        efficiency_baseline_km: $('#efficiency_baseline_km').val(),
        need_obd: $('#need_obd').val(),
        obd_device_no: $('#obd_device_no').val().trim(),
        use_mr_car: $('#use_mr_car').val(),
        registration_date: $('#registration_date').val(),
        first_effective_date: $('#first_effective_date').val(),
        entry_date: $('#entry_date').val(),
        exit_date: $('#vehicle_exit_date').val(),
        schedule_expiration_date: $('#schedule_expiration_date').val(),
        supplier_id: $('#supplier_id').val(),
        contract_id: $('#contract_id').val(),
        country_id: $('#country_id').val(),
        city_id: $('#city_id').val(),
        region_id: $('#region_id').val(),
        department_id: $('#department_id').val(),
        project_id: $('#project_id').val(),
        office_id: $('#office_id').val(),
        location_id: $('#location_id').val(),
        schedule_id: $('#schedule_id').val()
    };

    if (!data.plate_number) {
        showVehicleError('Plate number is required');
        return;
    }

    $.ajax({
        url: 'api/vehicles.php?action=save',
        method: 'POST',
        dataType: 'json',
        data: data,
        success: function (res) {
            if (res.status !== 'success') {
                showVehicleError(res.message || 'Save failed');
                return;
            }

            hideVehicleModal();
            _pageState.page = 1;
            loadVehicles();
            showVehicleSuccess('Vehicle saved successfully');
        },
        error: function () {
            showVehicleError('Server error while saving vehicle');
        }
    });
}

function editVehicle(vehicle) {
    clearVehicleForm();

    $('#vehicle_id').val(vehicle.id || '');
    $('#plate_number').val(vehicle.plate_number || '');
    var ownerOpt = $('#vehicle_owner option').filter(function() { return $(this).text() === vehicle.owner; });
    if (ownerOpt.length) { $('#vehicle_owner').val(ownerOpt.val()); } else { $('#vehicle_owner').val(''); }
    $('#vehicle_property').val(vehicle.property || '');
    var modelOpt = $('#vehicle_model option').filter(function() { return $(this).text() === vehicle.vehicle_model; });
    if (modelOpt.length) { $('#vehicle_model').val(modelOpt.val()); } else { $('#vehicle_model').val(''); }
    var typeOpt = $('#vehicle_type option').filter(function() { return $(this).text() === vehicle.vehicle_type; });
    if (typeOpt.length) { $('#vehicle_type').val(typeOpt.val()); } else { $('#vehicle_type').val(''); }
    $('#year_of_manufacturing').val(vehicle.year_of_manufacturing || '');
    $('#vehicle_status').val(vehicle.vehicle_status || 'Active');
    $('#vehicle_use_type').val(vehicle.vehicle_use_type || '');
    $('#vehicle_source').val(vehicle.vehicle_source || '');
    $('#vehicle_displacement').val(vehicle.displacement || '');
    $('#vehicle_seats').val(vehicle.seats || '');
    $('#standard_fuel_consumption').val(vehicle.standard_fuel_consumption_l_per_100km || '');
    $('#efficiency_baseline_km').val(vehicle.efficiency_baseline_km || '');
    $('#need_obd').val(String(Number(vehicle.need_obd || 0)));
    $('#obd_device_no').val(vehicle.obd_device_no || '');
    $('#use_mr_car').val(String(Number(vehicle.use_mr_car || 0)));
    $('#registration_date').val(normalizeDateInput(vehicle.registration_date));
    $('#first_effective_date').val(normalizeDateInput(vehicle.first_effective_date));
    $('#entry_date').val(normalizeDateInput(vehicle.entry_date));
    $('#vehicle_exit_date').val(normalizeDateInput(vehicle.exit_date));
    $('#schedule_expiration_date').val(normalizeDateInput(vehicle.schedule_expiration_date));
    $('#supplier_id').val(vehicle.supplier_id || '');
    $('#contract_id').val(vehicle.contract_id || '');
    $('#country_id').val(vehicle.country_id || '');
    $('#city_id').val(vehicle.city_id || '');
    $('#region_id').val(vehicle.region_id || '');
    $('#department_id').val(vehicle.department_id || '');
    $('#project_id').val(vehicle.project_id || '');
    $('#office_id').val(vehicle.office_id || '');
    $('#location_id').val(vehicle.location_id || '');
    $('#schedule_id').val(vehicle.schedule_id || '');

    $('#modalTitle').text('Edit Vehicle');
    showVehicleModal();
}

function deleteVehicle(id) {
    if (!id || !confirm('Are you sure you want to delete this vehicle?')) {
        return;
    }

    $.ajax({
        url: 'api/vehicles.php?action=delete',
        method: 'POST',
        dataType: 'json',
        data: { id: id },
        success: function (res) {
            if (res.status !== 'success') {
                showVehicleError(res.message || 'Delete failed');
                return;
            }

            _pageState.page = 1;
            loadVehicles();
            showVehicleSuccess('Vehicle deleted successfully');
        },
        error: function () {
            showVehicleError('Server error during delete');
        }
    });
}

function renderPagination(meta) {
    var page = meta.page || 1;
    var totalPages = meta.total_pages || 1;
    var total = meta.total || 0;
    var perPage = meta.per_page || 50;

    $('#paginationInfo').text('Showing ' + ((page - 1) * perPage + 1) + '-' + Math.min(page * perPage, total) + ' of ' + total);

    var html = '';
    if (page > 1) html += '<li class="page-item"><a class="page-link" data-page="' + (page - 1) + '" href="#">«</a></li>';
    for (var i = Math.max(1, page - 2); i <= Math.min(totalPages, page + 2); i++) {
        html += '<li class="page-item' + (i === page ? ' active' : '') + '"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>';
    }
    if (page < totalPages) html += '<li class="page-item"><a class="page-link" data-page="' + (page + 1) + '" href="#">»</a></li>';
    $('#paginationNav').html(html);
}

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

    if (normalized === 'active') {
        return '<span class="badge bg-success">Active</span>';
    }
    if (normalized === 'in workshop') {
        return '<span class="badge bg-warning text-dark">In Workshop</span>';
    }
    if (normalized === 'inactive') {
        return '<span class="badge bg-secondary">Inactive</span>';
    }

    return `<span class="badge bg-info text-dark">${escapeHtml(status || 'Unknown')}</span>`;
}

function showVehicleModal() {
    new bootstrap.Modal(document.getElementById('vehicleModal')).show();
}

function hideVehicleModal() {
    const modalEl = document.getElementById('vehicleModal');
    const instance = bootstrap.Modal.getInstance(modalEl);

    if (instance) {
        instance.hide();
    }
}

function clearVehicleForm() {
    const form = document.getElementById('vehicleForm');
    if (form) {
        form.reset();
    }

    $('#vehicle_id').val('');
    $('#vehicle_status').val('Active');
    $('#need_obd').val('0');
    $('#use_mr_car').val('0');
}

function normalizeDateInput(value) {
    if (!value) {
        return '';
    }

    return String(value).slice(0, 10);
}

function populateSelect(selector, options, placeholder, valueField) {
    const $select = $(selector);
    const currentValue = $select.val();
    valueField = valueField || 'id';
    let html = `<option value="">${escapeHtml(placeholder || 'Select option')}</option>`;

    $.each(options, function (_, option) {
        var val = option[valueField];
        html += `<option value="${escapeHtml(val != null ? val : '')}">${escapeHtml(option.label)}</option>`;
    });

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

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

function showVehicleSuccess(message) {
    alert(message);
}

function showVehicleError(message) {
    alert(message);
}

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