<template>
    <div class="innerOrderSummaryArea orderOverviewArea">
        <!-- Load failure: the basket AJAX call failed, so show an error + retry rather than a blank/zeroed summary -->
        <div class="orderSummaryBox alert alert-error" v-show="hasLoadError" v-cloak>
            <h4>We couldn't load your order</h4>
            <p>Something went wrong loading your basket. Please try again.</p>
            <button type="button" class="btn" @click="retryLoad" :disabled="busy">Retry</button>
        </div>

        <div class="orderSummaryBox" v-show="loaded && !hasLoadError" v-cloak>
            <h4>Review your order <span v-if="orderId">(Order # {{ orderId }})</span></h4>

            <div class="innerSummary">
                <!-- Basket Items (read-only) -->
                <basket-items
                    :items="basket.items"
                    :hide-inputs="true"
                    :placeholder-image="basketPlaceholderImage"
                    :show-sizes="config.itemsSizes"
                    :site="config.site"
                />

                <!-- Totals -->
                <basket-totals
                    :basket="basket"
                    :currencies="currencies"
                    :errors="errors"
                    :messages="messages"
                    :coupon-enabled="config.couponEnabled"
                    :show-vat="config.basketShowVat"
                    :hide-inputs="true"
                    @update-coupon-code="updateCouponCode"
                    @validate-coupon="validateCoupon"
                    @clear-coupon="clearCoupon"
                />
            </div>
        </div>

        <!-- User Details Overview (read-only) -->
        <div class="userDetailsOverview" v-show="loaded && !hasLoadError">
            <details-overview
                :basket="basket"
                :billing-country="billingCountryName"
                :shipping-country="shippingCountryName"
                :billing-state="billingStateName"
                :shipping-state="shippingStateName"
            />
        </div>

        <!-- Back Button -->
        <div class="overviewBackButtons desktopBackButton">
            <a href="/shop/checkout/basket.php" class="backToBasket">Go Back & Edit Details</a>
        </div>
    </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
import BasketItems from './sections/basket_items.vue';
import BasketTotals from './sections/basket_totals.vue';
import DetailsOverview from './overview/details_overview.vue';

export default {
    name: 'mtc-checkout-overview',

    provide() {
        return {
            formatPrice: this.multiCurrency
        };
    },

    components: {
        BasketItems,
        BasketTotals,
        DetailsOverview
    },

    props: {
        orderId: {
            type: [String, Number],
            default: null
        },
        initialConfig: {
            type: Object,
            default: () => ({})
        }
    },

    computed: {
        ...mapState('checkout', [
            'basket',
            'busy',
            'loaded',
            'currencies',
            'countries',
            'config',
            'errors',
            'messages',
            'state_list',
            'basket_placeholder_image'
        ]),

        basketPlaceholderImage() {
            return this.basket_placeholder_image;
        },

        // True once loading finished but the basket AJAX call failed.
        hasLoadError() {
            return this.loaded && !!this.errors.ajax_load;
        },

        billingCountryName() {
            const code = this.basket.address?.billing?.country;
            return this.countries?.[code] || code || '';
        },

        shippingCountryName() {
            const code = this.basket.address?.shipping?.country;
            return this.countries?.[code] || code || '';
        },

        billingStateName() {
            const code = this.basket.address?.billing?.state;
            const states = this.state_list?.billing;
            return states?.[code] || null;
        },

        shippingStateName() {
            const code = this.basket.address?.shipping?.state;
            const states = this.state_list?.shipping;
            return states?.[code] || null;
        }
    },

    created() {
        // Merge any props config
        if (this.initialConfig && Object.keys(this.initialConfig).length) {
            this.SET_CONFIG(this.initialConfig);
        }

        // Set hide_inputs to true for overview page (always read-only)
        this.SET_HIDE_INPUTS(1);

        // Initialize - fetches all data via AJAX
        this.initFromBootstrap();
    },

    methods: {
        ...mapActions('checkout', [
            'initFromBootstrap',
            'fetchBasket',
            'callUpdate',
            'validateCoupon'
        ]),

        ...mapMutations('checkout', [
            'SET_CONFIG',
            'SET_HIDE_INPUTS',
            'SET_BASKET_FIELD'
        ]),

        /**
         * Update coupon code in store
         */
        updateCouponCode(code) {
            this.SET_BASKET_FIELD({ path: 'coupon_code', value: code });
        },

        /**
         * Clear applied coupon
         */
        clearCoupon() {
            this.callUpdate({ action: 'clear_coupon' });
        },

        /**
         * Retry loading the basket after a failed fetch.
         */
        retryLoad() {
            this.fetchBasket();
        },

        /**
         * Multi-currency formatting helper
         */
        multiCurrency(value) {
            if (this.$options.filters && this.$options.filters.multi_currency) {
                return this.$options.filters.multi_currency(value);
            }
            const currency = this.currencies?.GBP || { symbol: '\u00A3', ratio: 1 };
            const amount = parseFloat(value) * (currency.ratio || 1);
            return currency.symbol + amount.toFixed(2);
        }
    }
};
</script>
