Vue.component('subscription-preferences', {

    props: [
        "dataUrl",
        "saveDataUrl",
        "labels",
    ],

    data: function() {
        return {
            sub_preferences: [],
            allowed_intervals: [],
            isBusy: false,
            message: '',
            messageType: '', // 'success' or 'error'
            all_ticked: {
                is_allowed: false,
                is_required: false,
                can_be_paused: false,
                max_number_of_issues: false,
                interval_multiplier: false,
                interval: '',
                discount_percentage: false
            },
        };
    },

    created: function() {
        this.fetchSubscriptionPreferences();
    },

    mounted: function() {
        // Initialize jQuery UI tooltips for subscription preference help icons
        this.$nextTick(function() {
            if (typeof jQuery !== 'undefined' && jQuery.fn.tooltip) {
                jQuery('.subscription-tooltip').tooltip({
                    position: {
                        my: "left center",
                        at: "right+10 center",
                        collision: "flipfit flip"
                    },
                    show: {
                        effect: "fadeIn",
                        duration: 150,
                        delay: 300
                    },
                    hide: {
                        effect: "fadeOut",
                        duration: 100
                    },
                    track: false
                });
            }
        });
    },

    methods: {

        fetchSubscriptionPreferences: function() {
            const that = this;

            fetch(this.dataUrl, {
                method: 'GET'
            })
            .then(response => response.json())
            .then(data => {

                let serverData = data.data;

                const preferences = serverData.map(pref => {

                    if(pref.interval === null) {
                        pref.interval = '';
                    }

                    return pref;

                });


                that.sub_preferences = data.data;
                that.allowed_intervals = data.allowed_intervals;
            })
            .catch(e => {
                //console.log(e);
            });
        },

        saveData: function() {
            const that = this;

            let submit_data = {
                data: this.sub_preferences,
            };

            this.isBusy = true;

            fetch(this.saveDataUrl, {
                method: 'POST',
                body: JSON.stringify(submit_data),
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                that.isBusy = false;
                that.message = 'Subscription preferences saved successfully!';
                that.messageType = 'success';
                setTimeout(function() {
                    that.message = '';
                    that.messageType = '';
                }, 5000);
            })
            .catch(error => {
                that.isBusy = false;
                that.message = 'Error saving subscription preferences: ' + error.message;
                that.messageType = 'error';
                console.error('Save error:', error);
            });
        },

        updateAll: function(property_name) {
            for (let i = 0; i < this.sub_preferences.length; i++) {
                this.sub_preferences[i][property_name] = this.all_ticked[property_name];
            }
        },

    },

    template: `
        <section>

            <table class="manage-items" border="0">

                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Item variation</th>
                        <th>
                            Is allowed?
                            <span class="subscription-tooltip" title="Enable subscription option for this product. If checked, customers can subscribe to regular deliveries.">ⓘ</span>
                        </th>
                        <th>
                            Is required?
                            <span class="subscription-tooltip" title="Force customers to subscribe (hide one-time purchase option). Use for subscription-only products.">ⓘ</span>
                        </th>
                        <th>
                            Can be paused?
                            <span class="subscription-tooltip" title="Allow customers to pause/resume their subscription. Recommended: Yes for flexibility.">ⓘ</span>
                        </th>
                        <th>
                            Max number of issues
                            <span class="subscription-tooltip" title="Maximum deliveries before subscription ends. Leave empty for unlimited subscriptions. Examples: 3 for trial packs, 6 for starter bundles, 12 for annual programs, 24 for 2-year courses, or blank for ongoing subscriptions.">ⓘ</span>
                        </th>
                        <th>
                            <span v-text="labels.interval_multiplier || 'Min. interval multiplier'"></span>
                            <span class="subscription-tooltip" title="How often to deliver, based on the interval unit. Think of this as 'Deliver every X [intervals]'. Examples with MONTHS: 1 = monthly (every 1 month), 2 = bi-monthly (every 2 months), 3 = quarterly (every 3 months), 6 = twice yearly. Examples with WEEKS: 1 = weekly, 2 = fortnightly (every 2 weeks), 4 = monthly (every 4 weeks). Examples with DAYS: 7 = weekly (every 7 days), 14 = fortnightly, 30 = monthly. Most common: 1 for regular monthly/weekly subscriptions.">ⓘ</span>
                        </th>
                        <th>
                            <span v-text="labels.interval || 'Min. interval'"></span>
                            <span class="subscription-tooltip" title="Time unit for delivery frequency. Options: days (for daily/weekly needs like vitamins), weeks (for bi-weekly prescriptions), months (for standard monthly supplies). Common: months for most medications, weeks for short-term treatments.">ⓘ</span>
                        </th>
                        <th>
                            Discount (%)
                            <span class="subscription-tooltip" title="Subscription discount percentage (optional). Set to 0% for no discount - subscriptions work at full price for convenience. Common discounts: 5% for basic loyalty, 10% for standard subscriptions, 15-20% for long-term commitments, 25%+ for bulk/annual plans.">ⓘ</span>
                        </th>
                    </tr>
                </thead>


                <tbody class="tabular">

                    <tr v-for="sub_config in sub_preferences">
                        <td
                            v-text="sub_config.shop_item.name"
                            style=""
                        ></td>
                        <td
                            v-text="sub_config.shop_item_size ? sub_config.shop_item_size.size : ''"
                            style="vertical-align: middle"
                        ></td>
                        <td style="">
                            <input
                                type="checkbox"
                                true-value="1"
                                v-model="sub_config.is_allowed"
                            />
                        </td>
                        <td style="">
                            <input
                                type="checkbox"
                                true-value="1"
                                v-model="sub_config.is_required"
                            />
                        </td>
                        <td style="">
                            <input
                                type="checkbox"
                                true-value="1"
                                v-model="sub_config.can_be_paused"
                            />
                        </td>
                        <td>
                            <input
                                type="number"
                                v-model="sub_config.max_number_of_issues"
                                style="max-width: 144px;"
                            />
                        </td>
                        <td>
                            <input
                                type="number"
                                v-model="sub_config.interval_multiplier"
                                style="max-width: 144px;"
                            />
                        </td>
                        <td style="width:130px;">
                            <select
                                v-model="sub_config.interval"
                                style="width:100%;min-width:140px;"
                            >
                                <option value="">Select interval</option>

                                <option v-for="allowed_interval in allowed_intervals"
                                    :value="allowed_interval"
                                    v-text="allowed_interval"
                                ></option>
                            </select>
                        </td>
                      <td>
                        <input
                            type="number"
                            v-model="sub_config.discount_percentage"
                        />
                      </td>
                    </tr>

                    <tr style="background-color:#dddddd" v-if="sub_preferences.length > 1">
                        <th
                            v-text="'Update all'"
                        ></th>
                        <td
                            v-text=""
                        ></td>
                        <td style="padding-top: 3px; vertical-align: middle;">
                            <input
                                type="checkbox"
                                value="1"
                                v-model="all_ticked.is_allowed"
                                @change="updateAll('is_allowed')"
                            />
                        </td>
                        <td style="padding-top: 3px; vertical-align: middle;">
                            <input
                                type="checkbox"
                                value="1"
                                v-model="all_ticked.is_required"
                                @change="updateAll('is_required')"
                            />
                        </td>
                        <td style="padding-top: 3px; vertical-align: middle;">
                            <input
                                type="checkbox"
                                value="1"
                                v-model="all_ticked.can_be_paused"
                                @change="updateAll('can_be_paused')"
                            />
                        </td>
                        <td>
                            <input
                                type="number"
                                v-model="all_ticked.max_number_of_issues"
                                @change="updateAll('max_number_of_issues')"
                                style="max-width: 144px;"
                            />
                        </td>
                        <td>
                            <input
                                type="number"
                                v-model="all_ticked.interval_multiplier"
                                @change="updateAll('interval_multiplier')"
                                style="max-width: 144px;"
                            />
                        </td>
                        <td style="width:130px;">
                            <select
                                v-model="all_ticked.interval"
                                @change="updateAll('interval')"
                                style="width:100%;min-width:140px;"
                            >
                                <option value="">Select interval</option>

                                <option v-for="allowed_interval in allowed_intervals"
                                    :value="allowed_interval"
                                    v-text="allowed_interval"
                                ></option>
                            </select>
                        </td>
                      <td>
                        <input
                            type="number"
                            v-model="all_ticked.discount_percentage"
                            @change="updateAll('discount_percentage')"
                        />
                      </td>
                    </tr>
                </tbody>

            </table>

            <div v-if="message" :style="messageType === 'success' ? 'padding: 10px; margin: 15px 0; border-radius: 4px; background-color: #d4edda; border: 1px solid #c3e6cb; color: #155724;' : 'padding: 10px; margin: 15px 0; border-radius: 4px; background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24;'">
                {{ message }}
            </div>

            <div class="row">
                <button
                    @click.prevent="saveData"
                    class="btn btn-secondary"
                    v-text="isBusy ? 'Saving...' : 'Save subscription preferences'"
                    :disabled="isBusy"
                ></button>
            </div>

        </section>
    `,

});
