define([
    'jquery',
    'Magento_Ui/js/modal/confirm',
    'mage/translate',
    'mageUtils',
    'mage/url'
], function ($, confirm, $t, utils, url) {
    'use strict';

    return function (Massactions) {
        return Massactions.extend({
            applyAction: function (actionIndex) {
                var data = this.getSelections(),
                    action = this.getAction(actionIndex),
                    callback = this._getCallback(action, data);

                if (!data.total) {
                    this._showNoItemsMessage();
                    return this;
                }

                if (action.type === 'order_courier') {
                    this.showPickupModal(action, data);
                } else if (action.confirm) {
                    this._confirm(action, callback);
                } else {
                    callback();
                }

                this.close();
                return this;
            },

            showPickupModal: function (action, data) {
                $.ajax({
                    url: action.url,
                    type: 'GET',
                    dataType: 'json',
                    showLoader: true
                }).done(function (response) {
                    if (response.success) {
                        var dates = Object.keys(response.dates);
                        var firstDate = dates[0];
                        var modalHtml = `
                        <div>
                            <p><em>${$t('To cancel a courier pickup, contact customer service or your sales representative.')}</em></p>
                            <label><strong>${$t('Select day of collection')}:</strong></label>
                                <select id="pickup-date">
                                    ${dates.map(function (date) {
                            return `<option value="${date}">${date}</option>`;
                        }).join('')}
                                </select>
                                <br><br>
                                <label><strong>${$t('Select a time frame')}:</strong></label>
                                <select id="pickup-time">
                                    ${response.dates[firstDate].map(function (time) {
                            return `<option value="${time}">${time}</option>`;
                        }).join('')}
                                </select>
                        </div>
                    `;

                        confirm({
                            title: $t('Schedule a pickup by ORLEN courier'),
                            content: modalHtml,
                            actions: {
                                confirm: function () {
                                    var date = document.getElementById('pickup-date').value;
                                    var time = document.getElementById('pickup-time').value;

                                    var itemsType = data.excludeMode ? 'excluded' : 'selected';
                                    var selections = {};
                                    selections[itemsType] = data[itemsType];
                                    if (!selections[itemsType] || !selections[itemsType].length) {
                                        selections[itemsType] = false;
                                    }

                                    selections['pickup_date'] = date;
                                    selections['pickup_time'] = time;

                                    _.extend(selections, data.params || {});

                                    utils.submit({
                                        url: action.url.replace('availablepickups', 'massOrderCourier'),
                                        data: selections
                                    });
                                },
                                cancel: function () {}
                            }
                        });

                        $(document).on('change', '#pickup-date', function () {
                            var selectedDate = $(this).val();
                            var times = response.dates[selectedDate] || [];
                            var timeOptions = times.map(function (time) {
                                return `<option value="${time}">${time}</option>`;
                            }).join('');
                            $('#pickup-time').html(timeOptions);
                        });
                    } else {
                        require(['Magento_Ui/js/modal/alert'], function (alert) {
                            alert({ content: response.message });
                        });
                    }
                }).fail(function () {
                    require(['Magento_Ui/js/modal/alert'], function (alert) {
                        alert({ content: $t('Failed to load pickup options window.') });
                    });
                });
            },
        });
    };
});
