var showCorrectFields = function () {
    var gocarsDisplay = jQuery('[name="gocars_display"]').val();
    var shortcodeID = jQuery('[name="shortcode"]').attr('data-post');

    if (jQuery('[name="gocars_display"]').length == 0) {
        return;
    }

    if (gocarsDisplay == 'terms') {
        jQuery('.shortcode-table').hide();
        jQuery('[name="shortcode"]').val('[terms id="' + shortcodeID + '"]');
    } else if (gocarsDisplay == 'fleet') {
        jQuery('[for="fleet_number"]').show();
        jQuery('[name="fleet_number"]').show();
        jQuery('.fleet_fields').show();
        jQuery('.search_form_fields').hide();
        jQuery('[name="shortcode"]').val('[fleet id="' + shortcodeID + '"]');
    } else {
        jQuery('[for="fleet_number"]').hide();
        jQuery('[name="fleet_number"]').hide();
        jQuery('.fleet_fields').hide();
        jQuery('.search_form_fields').show();
        jQuery('[name="shortcode"]').val('[search_form id="' + shortcodeID + '"]');
    }
};

jQuery(document).ready(function () {
    showCorrectFields();

    jQuery('#gocars_shortcode_meta input, #gocars_shortcode_meta select').on('change', function () {
        showCorrectFields();
    });

    jQuery('[name="display_selected_vehicles"]').on('change', function () {
        jQuery('.selected-vehicles-row').toggle();
    });

    jQuery('[name="display_selected_locations"]').on('change', function () {
        jQuery('.selected-locations-row').toggle();
    });

    jQuery('[name="display_elements_wrapper"], [name="display_keypoints"]').on('change', function () {
        jQuery(this).parents('table').find('.elements-wrapper-row').toggle();
    });

    jQuery('.tab-links a').on('click', function (e) {
        var currentAttrValue = jQuery(this).attr('href');
        jQuery('.tab-content ' + currentAttrValue)
            .show()
            .siblings()
            .hide();
        jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
        e.preventDefault();
    });

    //RANK MATH
    if (jQuery('.rank-math-notice').length > 0) {
        jQuery('.rank-math-notice code').each(function () {
            if (jQuery(this).text() == 'gocars_shortcode' || jQuery(this).text() == 'gocars_db') {
                jQuery(this).parents('.rank-math-notice').find('.notice-dismiss').click();
            }
        });
    }

    jQuery('[name="show_footer"], [name="show_border"]').on('input', function (e) {
        var inputName = jQuery(this).attr('name');
        if (jQuery(this).val() == 'show') {
            jQuery('tr[data-input="' + inputName + '"]').show();
        } else {
            jQuery('tr[data-input="' + inputName + '"]').hide();
        }
    });

    jQuery('.select-2-item').on('select2:unselect', function (e) {
        e.preventDefault();
        if (jQuery('#car_info_display').val()[0] == undefined) {
            // Sort the array based on a predefined order
        }

        showFeatures();
        showButton();
    });

    jQuery('.select-2-item').on('select2:select', function (e) {
        showFeatures();
        showButton();
    });

    jQuery('.select-2-all').on('click', function (e) {
        e.preventDefault();

        jQuery(this).parents('.select-2-label').find('.select-2-item > option').prop('selected', true);
        jQuery(this).parents('.select-2-label').find('.select-2-item').trigger('change');
        jQuery('.features-row').show();
        jQuery('.button-row').show();
    });

    if (jQuery('[name="gocars_database"] option').length <= 1 && jQuery('[name="gocars_database"]').length > 0) {
        alert('Please create a Database first from the Gocars Online Settings');
    }

    var select2 = false;
    if (typeof jQuery !== 'undefined' && typeof jQuery.fn.select2 !== 'undefined') {
        // jQuery and Select2 are available, initialize Select2
        select2 = true;
    }

    var selectedValues = jQuery('#car_info_display').data('value');
    if (selectedValues != undefined && select2) {
        jQuery('.select-2-item.car-info')
            .select2({
                placeholder: 'Select Car Info',
                allowClear: true,
                multiple: true,
                minimumSelectionLength: 1,
                debug: true
            })
            .val(selectedValues)
            .trigger('change');

        if (selectedValues.length == 0) {
            jQuery('#car_info_display > option').prop('selected', true);
            jQuery('#car_info_display').trigger('change');
            jQuery('.features-row').show();
            jQuery('.button-row').show();
        }
    }

    var selectedFeatures = jQuery('#car_features').data('value');
    if (selectedFeatures != undefined && select2) {
        jQuery('.select-2-item.car-features')
            .select2({
                placeholder: 'Select Car Features',
                allowClear: true,
                multiple: true,
                minimumSelectionLength: 1,
                debug: true
            })
            .val(selectedFeatures)
            .trigger('change');
    }

    var selectedVehicles = jQuery('#selected_vehicles').data('value');
    if (selectedVehicles != undefined && select2) {
        jQuery('.select-2-item.selected_vehicles')
            .select2({
                placeholder: 'Select All',
                allowClear: true,
                multiple: true,
                minimumSelectionLength: 1,
                debug: true
            })
            .val(selectedVehicles)
            .trigger('change');
    }

    var selectedLocations = jQuery('#selected_locations').data('value');
    if (selectedLocations != undefined && select2) {
        jQuery('.select-2-item.selected_locations')
            .select2({
                placeholder: 'Select All',
                allowClear: true,
                multiple: true,
                minimumSelectionLength: 1,
                debug: true
            })
            .val(selectedLocations)
            .trigger('change');
    }

    var elementsWrapper = jQuery('#repeater-container .select-2-item.elements_wrapper');
    if (elementsWrapper.length > 0 && select2) {
        elementsWrapper.each(function (index) {
            initializeSelect2(jQuery(this));
        });
    }
    // Function to initialize select2 on a single element
    function initializeSelect2(element) {
        element.select2({
            placeholder: 'Select All',
            allowClear: true,
            multiple: true,
            minimumSelectionLength: 1,
            debug: true
        });
    }
    // Function to update the hidden input with serialized data
    function updateElementsWrapperData() {
        var data = [];
        jQuery('#fleet_fields #repeater-container .elements_wrapper').each(function () {
            var rowValues = jQuery(this).val();
            if (Array.isArray(rowValues) && rowValues.length > 0) {
                data.push(rowValues);
            }
        });
        jQuery('#elements_wrapper_data').val(JSON.stringify(data));

        var keypoints_data = [];
        jQuery('#search_form_fields #repeater-container .single-keypoint').each(function () {
            var keypointValue = jQuery(this).val();
            if (keypointValue !== undefined && keypointValue !== null && keypointValue !== '') {
                keypoints_data.push(keypointValue);
            }
        });
        jQuery('#keypoints_data').val(JSON.stringify(keypoints_data));
    }

    jQuery('#fleet_fields, #search_form_fields').on('click', '.remove-field', function (e) {
        e.preventDefault();
        jQuery(this).parent('.field-group').remove();
        updateElementsWrapperData();
    });
    
    // Add field button click event
    jQuery('#add-field').on('click',function (e) {
        e.preventDefault();

        // Create a new field group
        var newFieldGroup = jQuery('<div class="field-group"></div>');

        // Clone the .repeater-field elements and append to the new field group
        var clonedField = jQuery('.hidden[data-id="fleet_fields"] .repeater-field').clone();
        clonedField.find('.select-2-item.elements_wrapper').attr('id', 'elements_wrapper-' + (jQuery('#fleet_fields #repeater-container .elements_wrapper').length + 1));
        newFieldGroup.append(clonedField);

        // Append the remove button
        // newFieldGroup.append('<button class="remove-field button">Remove</button>');
        newFieldGroup.append('<button class="remove-field button">Remove</button>');

        // Append the new field group to the container
        jQuery('#fleet_fields #repeater-container').append(newFieldGroup);
        // newFieldGroup.find('.select-2-item.elements_wrapper').replace('{INDEX}', jQuery('#repeater-container .elements_wrapper').length + 1);

        // Initialize select2 on the new select element
        initializeSelect2(newFieldGroup.find('.select-2-item.elements_wrapper'));
        // Update the hidden input with serialized data
        updateElementsWrapperData();

    });

    jQuery('#add-keypoint').on('click',function (e) {
        e.preventDefault();

        // Create a new field group
        var newFieldGroup = jQuery('<div class="field-group"></div>');

        // Clone the .repeater-field elements and append to the new field group
        var clonedField = jQuery('.hidden[data-id="search_form_fields"] .repeater-field').clone();
        clonedField.find('.single-keypoint').attr('id', 'keypoints-' + (jQuery('#search_form_fields #repeater-container .single-keypoint').length + 1));
        newFieldGroup.append(clonedField);

        // Append the remove button
        newFieldGroup.append('<button class="remove-field button">Remove</button>');

        // Append the new field group to the container
        jQuery('#search_form_fields #repeater-container').append(newFieldGroup);

        updateElementsWrapperData();

    });


    // Change event handler for dynamically added fields
    jQuery('#fleet_fields #repeater-container, #search_form_fields #repeater-container').on(
        'change',
        '.elements_wrapper, .single-keypoint',
        function () {
            updateElementsWrapperData();
        }
    );

    jQuery('#fleet_fields #repeater-container').on('select2:select select2:unselect', '.elements_wrapper', function () {
        updateElementsWrapperData();
    });

    // Update the hidden input with serialized data on page load
    updateElementsWrapperData();

    showFeatures();
    showButton();

    function showFeatures() {
        if (jQuery.inArray('features', jQuery('#car_info_display').val()) != -1) {
            jQuery('.features-row').show();
        } else {
            jQuery('.features-row').hide();
        }
    }

    function showButton() {
        if (jQuery.inArray('button', jQuery('#car_info_display').val()) != -1) {
            jQuery('.button-row').show();
        } else {
            jQuery('.button-row').hide();
        }
    }

    //SORTING
    if (jQuery('#car_info_display ~ .select2 .select2-selection__rendered').length > 0) {
        jQuery('#car_info_display ~ .select2 .select2-selection__rendered').sortable({
            containment: 'parent',
            items: '.select2-selection__choice',
            stop: function () {
                var sortedData = [];
                // Handle updates after sorting
                // You can retrieve the sorted order here
                jQuery(this)
                    .find('.select2-selection__choice')
                    .each(function () {
                        var optionTitle = jQuery(this)[0].title;
                        var carInfoOption = jQuery('#car_info_display option[title="' + optionTitle + '"]').val();
                        sortedData.push(carInfoOption);
                    });

                var options = jQuery('#car_info_display option');
                // Sort the options based on the defined order
                options.sort(function (a, b) {
                    var aValue = sortedData.indexOf(jQuery(a).val());
                    var bValue = sortedData.indexOf(jQuery(b).val());
                    return aValue - bValue;
                });

                // Remove existing options and append the sorted options
                jQuery('#car_info_display').empty().append(options);
            }
        });
    }

    if (jQuery('#selected_vehicles ~ .select2 .select2-selection__rendered').length > 0) {
        jQuery('#selected_vehicles ~ .select2 .select2-selection__rendered').sortable({
            containment: 'parent',
            items: '.select2-selection__choice',
            stop: function () {
                var sortedData = [];
                // Handle updates after sorting
                // You can retrieve the sorted order here
                jQuery(this)
                    .find('.select2-selection__choice')
                    .each(function () {
                        var optionTitle = jQuery(this)[0].title;
                        var carInfoOption = jQuery('#selected_vehicles option[title="' + optionTitle + '"]').val();
                        sortedData.push(carInfoOption);
                    });

                var options = jQuery('#selected_vehicles option');
                // Sort the options based on the defined order
                options.sort(function (a, b) {
                    var aValue = sortedData.indexOf(jQuery(a).val());
                    var bValue = sortedData.indexOf(jQuery(b).val());
                    return aValue - bValue;
                });

                // Remove existing options and append the sorted options
                jQuery('#selected_vehicles').empty().append(options);
            }
        });
    }

    if (jQuery('#selected_locations ~ .select2 .select2-selection__rendered').length > 0) {
        jQuery('#selected_locations ~ .select2 .select2-selection__rendered').sortable({
            containment: 'parent',
            items: '.select2-selection__choice',
            stop: function () {
                var sortedData = [];
                // Handle updates after sorting
                // You can retrieve the sorted order here
                jQuery(this)
                    .find('.select2-selection__choice')
                    .each(function () {
                        var optionTitle = jQuery(this)[0].title;
                        var carInfoOption = jQuery('#selected_locations option[title="' + optionTitle + '"]').val();
                        sortedData.push(carInfoOption);
                    });

                var options = jQuery('#selected_locations option');
                // Sort the options based on the defined order
                options.sort(function (a, b) {
                    var aValue = sortedData.indexOf(jQuery(a).val());
                    var bValue = sortedData.indexOf(jQuery(b).val());
                    return aValue - bValue;
                });

                // Remove existing options and append the sorted options
                jQuery('#selected_locations').empty().append(options);
            }
        });
    }

    if (typeof gocarsAdminSync !== 'undefined') {
        var $btn = jQuery('#gocars-refresh-remote-cache');
        var $status = jQuery('#gocars-refresh-remote-cache-status');
        if ($btn.length && gocarsAdminSync.post_id > 0) {
            $btn.on('click', function () {
                $btn.prop('disabled', true);
                $status.text(gocarsAdminSync.strings.refresh_working);
                jQuery
                    .post(gocarsAdminSync.ajax_url, {
                        action: 'gocars_refresh_shortcode_cache',
                        nonce: gocarsAdminSync.nonce,
                        post_id: gocarsAdminSync.post_id
                    })
                    .done(function (res) {
                        if (res && res.success) {
                            $status.text(gocarsAdminSync.strings.refresh_done);
                        } else {
                            $status.text(gocarsAdminSync.strings.refresh_fail);
                        }
                    })
                    .fail(function () {
                        $status.text(gocarsAdminSync.strings.refresh_fail);
                    })
                    .always(function () {
                        $btn.prop('disabled', false);
                    });
            });
        }
    }
});
