define([
    "jquery",
    "Magento_Checkout/js/view/payment/default",
    "mage/url",
    "Magento_Customer/js/customer-data",
    'Magento_Checkout/js/model/error-processor',
    'Magento_Checkout/js/model/full-screen-loader'
], function ($, Component, url, customerData, errorProcessor, fullScreenLoader) {
    "use strict";
    return Component.extend({
        defaults: {
            active: false,
            template: "Sibs_Sibs/payment/sibs_pbl"
        },
        initObservable() {
            this._super().observe(['active']);
            return this;
        },
        redirectAfterPlaceOrder: false,
        selectSibsPaymentMethod: function () {
            $('.paymentSPG').remove();
            $(".sibs_place_order_blik").show();
            $(".sibs_place_order_creditcard").show();
            $(".sibs_place_order_pbl").show();
            $(".sibs_place_order_xpay").show();
        },
        afterPlaceOrder: function () {
            fullScreenLoader.startLoader();
            let url_form = url.build("sibs/payment/pbl");

            $.post(url_form).done(function (response) {
                var form = response?.fields;
                $('.paymentSPG').remove();

                $('<form>', {
                    class: 'paymentSPG',
                    'spg-context': form?.formContext,
                    'spg-config': form?.formConfig,
                    'spg-signature': form?.formSignature,
                    'spg-style': form?.formStyle,
                }).appendTo('.payment-method-sibs-pbl');

                $.getScript(form?.widgetURL).done(function (script, textStatus) {
                    $('.sibs_place_order_pbl').hide();
                })
                    .fail(function (jqxhr, settings, exception) {
                        $("div.log").text("Triggered ajaxError handler.");
                        $('.sibs_place_order_pbl').show();
                    });

            })
                .fail(function (response) {
                    errorProcessor.process(response, this.messageContainer);
                })
                .always(function () {
                    let sessions = ['cart'];
                    customerData.invalidate(sessions);
                    customerData.reload(sessions, true);
                    fullScreenLoader.stopLoader();
                });
        },
        isActive() {
            var active = this.getCode() === this.isChecked();

            this.active(active);
            return active;
        },
        getCode() {
            return window.checkoutConfig.payment.pbl.code;
        },
        getTitle() {
            return window.checkoutConfig.payment.pbl.title;
        },
        getPaymentLogoSrc: function () {
            return window.checkoutConfig.payment.pbl.logoSrc;
        },
        getInstructions: function () {
            return window.checkoutConfig.payment.pbl.instructions;
        }
    });
});
