// phpcs:ignoreFile
define([
    "jquery",
    "uiComponent",
    "ko",
    "mage/translate",

], function (
    $,
    Component,
    ko,
    __,
) {
    'use strict';

    return Component.extend({
        widgetButton: null,
        _config: {},

        initialize: function (options) {
            this._super();
            this._config = options;

            const deliveryContainer = $('.order-shipping-method .admin__page-section-item-content');

            /* line break support with text only binding (\n character support) */
            $(deliveryContainer).find('strong').css({'white-space': 'pre-line'});
            $(deliveryContainer).find('span.price').css({'display': 'block'});

            deliveryContainer.append($(`
            <input type="hidden" id="orlen-paczka-point-id"/><br>
            <button class="orlen-widget"
                    data-type="pickup"
                    data-layout="tabs"
                    data-modal="true"
                    data-target="#orlen-paczka-point-id"
                    style="font-family: inherit;"
                    disabled>
                ${$.mage.__('Change target')}
            </button>
            `));

            this.widgetButton = $('button.orlen-widget');
            this.initWidgetScript();

            return this;
        },

        initWidgetScript: function () {
            const script = $('#orlen-widget-script');
            script.attr('src', script.attr('data-src'));
            script.on('load', () => {
                $('.orlen-widget-modal').on('orlenSelectPoint', this.setPoint.bind(this));
                this.widgetButton.removeAttr('disabled');
            });
        },

        setPoint: function (event) {
            const pointData = event.detail?.marker?.options;
            const pointId = pointData.id;
            const description = `${pointData?.groupName ?? ''}, \n${pointData?.addressLine ?? ''}, ${pointData?.city ?? ''} ${pointData?.postalCode ?? ''}`;

            if (!pointId) {
                alert(__('An error occurred while setting the pickup point.'));
                return;
            }

            this.widgetButton.attr('disabled', true);
            $.post(this._config.saveUrl, {
                description: description,
                destination_code: pointData.destinationCode,
                order_id: this._config.orderId
            }).done(function (data) {
                if (data.type === 'success') {
                    $('.order-shipping-method .admin__page-section-item-content strong').text(data.pointAddress);
                } else {
                    alert(data.message);
                }
            }).always(() => {
                this.widgetButton.removeAttr('disabled');
            });
        },
    });
});
