window.onload = function() {
    let pickupPointCarriersIds = JSON.parse(window.paxy_carriers_ids);
    let pickupPointCarriers = JSON.parse(window.paxy_carriers);
    let deliveryInputSelector = 'input[type=radio][name^="delivery_option"]';
    let initialized = false;
    let paxyInitialized = false;
    let selectedPoint;
    let selectedCourier;
    if (window.paxy_widget_selected_pickup_point) {
        try {
            selectedPoint = JSON.parse(window.paxy_widget_selected_pickup_point);
        } catch (e) {}
    }

    function updateSelectedPoint(data) {
        if (selectedPoint !== data) {
            selectedPoint = data;
            $.ajax({
                url: window.paxy_widget_update_cart_url,
                method: 'POST',
                data: {
                    pickup_point_id: selectedPoint ? selectedPoint.id : null,
                },
            });
        }
        toggleSubmitButton(!!selectedCourier && !selectedPoint);
        renderSelectedPointDetails();
    }

    function updateSelectedCourier(courier) {
        selectedCourier = courier;
        toggleSubmitButton(!!selectedCourier && !selectedPoint);
    }

    function renderSelectedPointDetails() {
        if (selectedPoint) {
            $('[data-paxy-selected-point-details]').html(`
                <p>
                  <strong>${window.paxy_widget_dictionary?.['selected_pickup_point'] ?? 'Wybrany punkt pickup'}:</strong>
                </p>
                <p>
                  ${selectedPoint.name}
                </p>
                <p>
                  ${selectedPoint.address}
                </p>
                <p>
                  ${selectedPoint.postCode} ${selectedPoint.city}
                </p>
            `);
        } else {
            $('[data-paxy-selected-point-details]').html('');
        }
    }

    function openWidget() {
        if (paxyInitialized && selectedCourier) {
            window.dispatchEvent(new CustomEvent('paxyWidgetOpen'));
        }   else {
            console.error('could not open paxy widget due to the fact that it was not initialized')
        }
    }

    function setWidgetConfig() {
        if (paxyInitialized && selectedCourier) {
            window.paxyWidget.setWidgetConfig({
                pickupPointsFullUrl: window.paxy_widget_api_url,
                componentType: "modal",
                couriers: [selectedCourier],
                language: window.paxy_widget_lang,
                dictionary: window.paxy_widget_dictionary,
                token: window.paxy_widget_token,
                showCouriersSelectInput: false,
                assetsPathPrefix: window.paxy_widget_assets_url + '?file='
            })
        }
    }

    function handleDeliveryChange(manual) {
        if (manual) {
            updateSelectedPoint(undefined);
        }

        var checkedDeliveryValue = $(deliveryInputSelector + ':checked').val();
        checkedDeliveryValue = checkedDeliveryValue ? checkedDeliveryValue.replace(',', '') : undefined;
        if (!!checkedDeliveryValue && pickupPointCarriersIds.includes(-(-(checkedDeliveryValue)))) {
            $('[data-paxy-section]').show();
            $('[data-paxy-pickup-point-id]').attr('required', true);
            const item = pickupPointCarriers.find(function(point) {
                return point.id_carrier ===  -(-(checkedDeliveryValue))
            })
            updateSelectedCourier(item.widget_pickup_point);
            setWidgetConfig();
        }   else {
            $('[data-paxy-section]').hide();
            $('[data-paxy-pickup-point-id]').attr('required', false);
            updateSelectedCourier(undefined);
            updateSelectedPoint(undefined);
        }
        renderSelectedPointDetails();
    }

    function toggleSubmitButton(disabled) {
        $('button[name="confirmDeliveryOption"]').attr('disabled', disabled);
        $('button#confirm_order').attr('disabled', disabled);
    }

    function init() {
        if (!initialized) {
            $('body').append('<paxy-widget></paxy-widget>')
            window.dispatchEvent(new CustomEvent('paxyWidgetBootstrap'));
            initialized = true;
        }
        handleDeliveryChange();
    }

    window.addEventListener("paxyWidgetInitialized", function(e) {
        paxyInitialized = true;
        handleDeliveryChange();
    })

    window.addEventListener('paxyWidgetPointSelected', function (e) {
        updateSelectedPoint(e.detail);
        window.dispatchEvent(new CustomEvent('paxyWidgetClose'));
    });

    if ($('.paxy-widget-select-point').length) {
        init();
    }

    $(document).on('paxyDisplayAfterCarrier', function () {
        init();
    });

    $(document).on('change', deliveryInputSelector, function () {
        if ($(this).is(':checked')) {
            handleDeliveryChange(true);
        }
    });

    $(document).on('click', '[data-paxy-select-point]', function(e) {
        $(e.target).attr('disabled', true)
        $(e.target).prepend('<div class="lds-dual-ring"></div>')
        openWidget();
        setTimeout(function() {
            $(e.target).attr('disabled', false);
            $(e.target).find('.lds-dual-ring').remove();
        }, 2500)
    });
}


$(document).on('ready', function () {
    var updateSuggestedPostcodes = (handler) => {
        var countryHandler = $(handler).find('select[name="id_country"]');
        var cityHandler = $(handler).find('input[name="city"]')
        var addressHandler = $(handler).find('input[name="address1"]')

        var country = countryHandler.find('option:selected').attr('data-iso-code')?.toLowerCase();
        var city = cityHandler.val() || undefined;
        var address = addressHandler.val() || undefined;

        if (!country || (window.paxy_widget_postcodes_allowed_country ?? []).indexOf(country) === -1) {
            return;
        }

        var postcodeHandler = $(handler).find('input[name="postcode"]');

        if (!!postcodeHandler) {
            var clearSuggestions = () => {
                var datalistHandler = $(postcodeHandler).closest('label').find('datalist');
                if (datalistHandler) {
                    datalistHandler.remove();
                }
            };

            if (city) {
                $.ajax({
                    url: window.paxy_widget_postcodes_url,
                    data: {
                        country: country,
                        city: city,
                        address: address,
                    },
                    dataType: 'json',
                    success: function (data) {
                        clearSuggestions();
                        if (data.success && Array.isArray(data.suggestedPostcodes)) {
                            var id = 'postcode-' + (Math.random() * 100).toFixed(0);

                            postcodeHandler.attr('list', id);

                            var parentHandler = postcodeHandler.closest('label');
                            var datalistHandler = $('<datalist>');
                            datalistHandler.attr('id', id);
                            data.suggestedPostcodes.forEach(function(postCode) {
                                datalistHandler.append($('<option>', {value: postCode, text: postCode}))
                            });

                            parentHandler.append(datalistHandler);
                            if (data.suggestedPostcodes.length === 1) {
                                postcodeHandler.val(data.suggestedPostcodes[0]);
                            }
                        }
                    },
                    error: function () {
                        clearSuggestions();
                    }
                });
            } else {
                clearSuggestions();
            }
        }


    };

    $('.address-fields').each(function () {
        var handler = $(this);

        updateSuggestedPostcodes(handler);

        $(this).on('change', 'select[name="id_country"]', function () {
            updateSuggestedPostcodes(handler);
        });

        $(this).on('blur', 'input[name="city"],input[name="address1"]', function () {
            updateSuggestedPostcodes(handler);
        });
    });
});
