<template>

    <div class="subscriptionItem" v-if="item && formUrl.length">

        <div class="subscriptionItem__loadingBox" v-if="loading">

            <loading-spinner
                    :loading="loading"
                    :show-loading-text="false"
                    loading-text="Updating subscription"
            ></loading-spinner>

        </div> <!-- .__loadingBox -->

        <div class="subscriptionItem__inner">

            <div class="subscriptionItem__title">

                <div
                        class="subscriptionItem__name"
                        v-html="sizeName"
                        v-if="sizeName.length"
                ></div> <!-- .subscriptionItem__name -->

                <div class="subscriptionItem__edit">

                    <button
                            type="button"
                            @click.prevent="toggleOptions"
                    >
                        
                        <i class="svgIcon">

                            <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    viewBox="0 0 512 512"
                                    width="16"
                                    height="16"
                            >
                                <path d="M471.6 21.7c-21.9-21.9-57.3-21.9-79.2 0L362.3 51.7l97.9 97.9 30.1-30.1c21.9-21.9 21.9-57.3 0-79.2L471.6 21.7zm-299.2 220c-6.1 6.1-10.8 13.6-13.5 21.9l-29.6 88.8c-2.9 8.6-.6 18.1 5.8 24.6s15.9 8.7 24.6 5.8l88.8-29.6c8.2-2.7 15.7-7.4 21.9-13.5L437.7 172.3 339.7 74.3 172.4 241.7zM96 64C43 64 0 107 0 160L0 416c0 53 43 96 96 96l256 0c53 0 96-43 96-96l0-96c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 96c0 17.7-14.3 32-32 32L96 448c-17.7 0-32-14.3-32-32l0-256c0-17.7 14.3-32 32-32l96 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L96 64z" fill="currentColor"/>
                            </svg>

                        </i>
                    </button>

                </div> <!-- .subscriptionItem__edit -->

            </div> <!-- .subscriptionItem__title -->

            <div class="subscriptionItem__options" v-if="optionsOpen">

                <product-size-select
                        :sizes="subscriptionSizes"
                        :selected-size-id="defaultSize"
                        select-label="Options"
                        :single-select="false"
                        :product-id="productID"
                        @sizechanged="updateSize"
                        :disable-chosen="true"
                ></product-size-select>
                

            </div> <!-- .subscriptionItem__options -->

            <div class="subscriptionItem__prices">

                <div class="multiPrice">
                    &pound;{{ subscriptionPrice }}
                </div> <!-- .multiPrice -->

                <div
                        class="subscriptionItem__frequency"
                        v-html="frequency"
                ></div> <!-- .__frequency -->

            </div> <!-- .subscriptionItem__prices -->

            <div class="subscriptionItem__buttons" v-if="optionsOpen">

                <button
                        type="button"
                        class="btn"
                        @click.prevent="updateSubscription"
                >
                    Update
                </button>

                <button
                        type="button"
                        class="btn btn-red"
                        @click.prevent="closeOptions(true)"
                >
                    Close
                </button>


            </div> <!-- .subscriptionItem__buttons -->

            <div
                    class="subscriptionItem__message"
                    v-if="message.length"
            >

                <div
                        :class="[hasError ? 'error' : 'success']"
                        v-text="message"
                ></div> <!-- .alert -->

            </div> <!-- .subscriptionItem__message -->

        </div> <!-- .subscriptionItem__inner -->

    </div> <!-- .subscriptionItem -->

</template>

<script>

import axios from 'axios';
import collect from "collect.js";

export default {

    props: {

        formUrl: {
            type: [String],
            default() {
                return ''
            }
        },

        subscriptionId: {
            type: [String, Number],
            default() {
                return 0
            }
        },

        item: {
            type: [Object, Array, Boolean],
            default() {
                return false
            }
        }
    },

    data() {

        return {
            defaultSize: 0,
            selectedSize: 0,
            optionsOpen: false,
            timeout: null,
            loading: false,
            message: '',
            hasError: false
        }

    },

    created() {

        //Set initial size
        this.selectedSize = parseInt(this.item.shop_item_size_id);

        if(isNaN(this.selectedSize)) {
            this.selectedSize = 0;
        }

        //Set default selected size
        this.defaultSize = this.selectedSize;


    },

    computed: {


        productTitle() {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

            const sizes = allSizes.filter(size => {

                const selectedID = parseInt(this.selectedSize);

                if(!isNaN(selectedID)) {

                    return selectedID == parseInt(size.id);
                }

            });

            if(sizes.length) {

                const size = sizes[0];

                return this.item.shop_item.name + ' (' + size.strength + ' x ' + size.size + ')';


            }

            return '';

        },

        subscriptionSizes() {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

            const sizes = allSizes.map(size => {

                if(typeof size.subscription_preference != 'undefined') {

                    if(size.subscription_preference?.is_allowed) {

                        size.price = size.subscription_preference.price;
                        size.price_exvat = size.subscription_preference.price_exvat;
                        size.sale_price = size.subscription_preference.sale_price;
                        size.sale_price_ex_vat = size.subscription_preference.sale_price_ex_vat;
                        size.price_per_pill = size.subscription_preference.price_per_pill;


                    }

                }

                return size;

            }).filter(size => size.subscription_preference?.is_allowed);

            return sizes;

        },

        productID() {
            return parseInt(this.item.shop_item.id);
        },

        subscriptionPrice() {

            let sizeSelected = this.item.shop_item.sizes.filter(size => size.id == this.selectedSize);

            if(sizeSelected.length) {
                sizeSelected = sizeSelected[0];

                let price = sizeSelected.subscription_preference.price;
                let salePrice = sizeSelected.subscription_preference.sale_price;

                if(salePrice < price && salePrice > 0 && price != salePrice) {
                    price = salePrice;
                }


                return price.toFixed(2);

            }

            return 0;
        },

        frequency() {

            let frequencyText = '';

            const selectedSize = this.getSize(this.selectedSize);

            if(selectedSize) {

                if(typeof selectedSize.subscription_preference != 'undefined') {

                    const prefs = selectedSize.subscription_preference;
                    const multiplier = parseInt(prefs.interval_multiplier);
                    let interval = prefs.interval;

                    if(!isNaN(multiplier) && interval.length) {

                        if(multiplier > 0) {

                            if (multiplier === 1 && interval == 'months') {
                                interval = 'month';
                            }else if(multiplier === 1 && interval == 'weeks') {
                                interval = 'week';
                            }else if(multiplier === 1 && interval == 'days') {
                                interval = 'day';
                            }

                            if(multiplier === 1) {
                                frequencyText = 'per ' + interval;
                            }else {
                                frequencyText = 'every ' + multiplier + ' ' + interval
                            }

                        }


                    }

                }

                return frequencyText;

            }

            return '';

        },
        
        sizeName() {
            
            const size = this.getSize(this.selectedSize);
     
            if(size?.size?.length) {
                
                return size.size;
                
            }
            
            return '';
        }

    },

    methods: {

        updateSubscription() {

            const vm = this;
            this.loading = true;

            axios.post(vm.formUrl, {
                subscription_item_id: this.item.id,
                shop_item_id: this.item.shop_item_id,
                shop_item_size_id: vm.selectedSize

            })
                    .then(function (response) {

                        const data = response.data;
                        const errors = data.errors;
                        const message = data.message;

                        if(errors) {
                            vm.showMessage(message, true);
                        }else{
                            vm.defaultSize = vm.selectedSize;
                            vm.showMessage(message, false);
                        }

                    })
                    .catch(function (error) {
                        vm.showMessage('Un unexpected error occurred, please try again later', true);
                    })
                    .finally(function () {
                        vm.loading = false;
                        vm.closeOptions(false);
                    });

        },

        getSize(id) {

            const allSizes = collect(this.item.shop_item.sizes).toArray();

            const sizes = allSizes.filter(size => {

                const sizeID = parseInt(size.id);
                const targetID = parseInt(id);

                if(sizeID == targetID && !isNaN(sizeID) && !isNaN(targetID)) {

                    return size;

                }

            });

            if(sizes.length) {
                return sizes[0];
            }

            return false;

        },

        updateSize(sizeID) {

            const selectedID = parseInt(sizeID);

            if(!isNaN(selectedID)) {
                this.selectedSize = selectedID;
            }

        },

        toggleOptions() {
            this.optionsOpen = !this.optionsOpen;

            if(!this.optionsOpen) {
                this.selectedSize = this.defaultSize;
            }else {
                this.message = '';
            }
        },

        closeOptions(reset) {

            this.optionsOpen = false;

            if(!this.optionsOpen && reset) {
                this.selectedSize = this.defaultSize;
            }

        },

        showMessage(message, hasError) {

            this.hasError = hasError;

            if(typeof hasError == 'undefined') {
                this.hasError = false;
            }

            this.message = message;


        }
    }

}
</script>

<style lang="less">

@import '@site/css/variables.less';
@import '@core/css/mixins.less';
@import '@site/../default/css/base/mixins.less';

.subscriptionItem {
    
    position: relative;
    .rems(16);
    line-height: 1.2em;
    padding: 16px 0;
    

    * {
        float: none;
        clear: both;
    }
    
    .loadingSpinner {
        
        .innerSpinner {
            
            div {
                background: @mtc_blue !important;
            }
            
        }
        
    }
    
    .btn {
        font-size: 16px !important;
        line-height: 31px !important;
    }

    &__loadingBox {

        position: absolute;
        z-index: 2;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: transparent;

        .loadingSpinner {
            height: 68px;
            margin-top: -30px;
        }

    }

    &__inner {
        position: relative;
        z-index: 1;
    }

    &__title {
        display: flex;
        gap: 0;
        flex-wrap: wrap;
        padding: 0 0 8px;
    }

    &__name {

        .rems(18);
        line-height: 1.2em;
        font-weight: 600;
        max-width: ~"calc(100% - 38px)";

    }

    &__edit {

        position: relative;
        top: -6px;
        margin-bottom: -20px;

        button {
            width: 38px;
            height: 38px;
            padding: 4px;
            cursor: pointer;
            background: transparent;
            border: none;
            transition: color 200ms linear;
            outline: 0;
            margin-left: 2px;
            color: @mtc_blue;

            &:hover, &:active, &:focus-visible {
                color: darken(@mtc_blue, 8%);
                transition: color 200ms linear;
            }

            .svgIcon {
                width: 16px;
                height: 16px;
                position: relative;
                top: -4px;
                
                svg {
                    height: 16px;
                }
            }
        }
    }

    &__prices {

        display: flex;
        flex-wrap: wrap;
        gap: 4px;

    }

    &__frequency {
        .rems(12);
        line-height: 24px;
        position: relative;
        top: 2px;
    }

    .multiPrice {

        .rems(18);
        line-height: 24px;
        font-weight: 600;
        flex: 0 0 auto;


        @media all and (max-width: 800px) {
            .rems(16);
        }

    }

    &__options {

        padding: 8px 0 0;

        .productSizes {
            max-width: 450px;

            .multipleSelect {
                gap: 16px;
            }
        }

    }

    &__buttons {

        padding: 16px 0;
        display: flex;
        gap: 12px;

        .btn {

            margin: 0;
            .rems(14);
            line-height: 1.2em;

        }

    }

    &__message {

        padding: 16px 0 0;

        .success, .error {
            border-radius: 12px;
            padding: 12px !important;
            .rems(14) !important;
            line-height: 1.2em;
            margin: 0;
            font-weight: 600 !important;
        }

        .success {
            padding: 16px 0 0 0 !important;
        }

        .error {
   
        }

    }

    .productSizes {

        .label {
            margin-bottom: 4px;
        }
        
        .optionsWrap {
            
            & > select {
                padding: 7px 12px;
                width: 100%;
                height: 40px;
            }
            
        }
        
        .sizeTextValue {
            height: 40px;
            font-weight: normal;
        }
        
    }

}

</style>
