window.addEventListener('load', function () {
    $('#searchForm').on('submit', function (e) {
        const searchKeyword = $("#searchText").val();
        const selectedCountry = $("#countryFilter").val();

        if (!searchKeyword) {
            $('#searchText').attr('disabled', 'disabled');
        }
        if (!selectedCountry) {
            $('#countryFilter').attr('disabled', 'disabled');
        }

        return true;
    });

    $('.btn-remove').on('click', function (e) {
        e.preventDefault();

        const itemId = $(this).data('id');
        const address = $(this).data('address');

        $modal = $('#remove-address-warning-modal');
        $modal.find('h4.modal-title').text(`Removing address: ${address}`);
        $modal.find('#removeBtn').data('id', itemId);
    });

    $('#removeBtn').on('click', function (e) {
        e.preventDefault();
        const itemId = $(this).data('id');
        window.location.href = `/addresses/${itemId}/remove`;
    })

    const address = $("#address").select2({
        placeholder: "Search By Address",
        width: "resolve",
        maximumSelectionSize: 1,
        minimumInputLength: 3,
        ajax: {
            url: "/geofence_area_anchor/getLocationByAddress",
            type: "GET",
            dataType: "json",
            delay: 250,
            data: function (params) {
                const query = {
                    address: params.term,
                    page: params.page || 1
                };
                return query;
            },
            processResults: function (res, params) {
                const { data, total } = res;
                params.page = params.page || 1;
                return {
                    results: data.map(item => ({
                        id: item.id,
                        text: item.address
                    })),
                    pagination: {
                        more: params.page * 20 < +total
                    }
                };
            }
        }
    });

    const city = $("#city").select2({
        placeholder: "Search By City",
        maximumSelectionSize: 1,
        minimumInputLength: 3,
        ajax: {
            url: "/geofence_area_city/getCities",
            type: "GET",
            dataType: "json",
            delay: 250,
            data: function (params) {
                const query = {
                    search_text: params.term,
                    page: params.page || 1
                };
                return query;
            },
            processResults: function (res, params) {
                const { data, total } = res;
                params.page = params.page || 1;
                return {
                    results: data.map(item => ({
                        id: item.id,
                        text: item.city_name
                    })),
                    pagination: {
                        more: params.page * 20 < +total
                    }
                };
            }
        }
    });

    $("#searchForm").on("submit", function(e) {

        let city_id = '';
        let city_name = '';

        if (city.select2("data").length) {
            city_id = city.select2("data")[0].id;
            city_name = city.select2("data")[0].text;
        }

        const address_text = address.select2("data").length
            ? address.select2("data")[0].text
            : '';
        
        const hidden_field =
            `<input type="hidden" name="city_id" value="${city_id}" />
            <input type="hidden" name="city_name" value="${city_name}" />
            <input type="hidden" name="address" value="${address_text}" />`;

        $(this).append(hidden_field);
    });

    $('#btnClear').on('click', function() {
        $('#city').empty();
        $('#address').empty();
        if ($('#radius_default').prop('checked') === false) {
            $('#rad').val('');
        }
        $('#lng').val('');
        $('#lat').val('');
    })

    $('#radius_default').on('change', function() {
        if ($(this).prop('checked')) {
            $('#rad').val('5'); // default 5000m
            $('#rad').css('pointer-events', 'none');
        } else {
            $('#rad').css('pointer-events', 'auto');
        }
    })
    $('#radius_default').trigger('change');
});