<template>
    <div class="totalRow delivery fullWidth" v-if="basket.has_physical_items">
        <div class="sectionTitle" v-if="showDeliveryOptions && hasMultipleOptions">
            Delivery
        </div>

        <div class="costTitle">
            <!-- Delivery Options Dropdown -->
            <div class="row" v-if="showDeliveryOptions && hasMultipleOptions">
                <chosen
                    :options="basket.delivery_options"
                    placeholder=""
                    :value="basket.delivery_selected"
                    @input="onDeliveryChange"
                    class="selectDelivery"
                    label="name"
                    track-by="id"
                    id="deliveryTime"
                    name="delivery"
                />
            </div>

            <!-- Single Option or No Options Message -->
            <div
                v-else
                class="messageBox"
                :class="{ 'error': noDeliveryOptions }"
            >
                <p v-if="basket.zone == 3 && noDeliveryOptions">
                    Unfortunately we are unable to post prescription medication to your country.
                    Please see the <a :href="deliveryPage">delivery page</a> for further information
                </p>
                <p v-else v-text="currentDeliveryName"></p>

                <input
                    type="hidden"
                    v-if="hasSingleOption"
                    :value="basket.delivery_selected"
                    name="delivery"
                />
            </div>
        </div>

        <!-- Delivery Cost -->
        <div class="cost" v-if="basket.cost_delivery > 0">
            <!-- v-html: formatPrice() returns multi_currency filter HTML markup -->
            <span v-html="formatPrice(basket.cost_delivery)"></span>
        </div>
        <div class="cost" v-else-if="basket.delivery_selected && basket.cost_delivery == 0">
            <span>FREE</span>
        </div>

        <!-- Delivery Instructions -->
        <div
            class="row deliveryInstructionsWrapper"
            v-if="showDeliveryOptions && hasMultipleOptions"
        >
            <label for="deliveryInstructions">
                Instructions (Optional)
            </label>
            <div class="inputWrap">
                <textarea
                    name="delivery_instructions"
                    id="deliveryInstructions"
                    v-model="localDeliveryInstructions"
                    class="text"
                ></textarea>
            </div>
        </div>

        <template v-else>
            <div
                v-if="basket.delivery_selected && basket.delivery_instructions && basket.delivery_instructions.length"
                class="deliveryInstructionsNote"
            >
                <small>Instructions: {{ basket.delivery_instructions }}</small>
            </div>
        </template>

        <!-- Delivery Error -->
        <div class="errorRow" v-if="hasDeliveryError">
            <div class="error">
                <p v-text="errors.delivery"></p>
                <a href="/customer-care/delivery/">Read more about deliveries</a>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'delivery-options',

    // Injected from parent checkout component (multiCurrency method).
    // Falls back to GBP formatting if used outside the checkout context.
    inject: {
        formatPrice: {
            default: () => (value) => {
                const amount = parseFloat(value) || 0;
                return '\u00A3' + amount.toFixed(2);
            }
        }
    },

    props: {
        basket: {
            type: Object,
            required: true
        },
        showDeliveryOptions: {
            type: Boolean,
            default: false
        },
        currentDeliveryName: {
            type: String,
            default: ''
        },
        errors: {
            type: Object,
            default: () => ({})
        },
        deliveryPage: {
            type: String,
            default: '/customer-care/delivery-information/'
        }
    },

    data() {
        return {
            localDeliveryInstructions: ''
        };
    },

    computed: {
        hasMultipleOptions() {
            return this.basket.delivery_options && this.basket.delivery_options.length > 1;
        },
        hasSingleOption() {
            return this.basket.delivery_options && this.basket.delivery_options.length === 1;
        },
        noDeliveryOptions() {
            return !this.basket.delivery_options || this.basket.delivery_options.length === 0;
        },
        hasDeliveryError() {
            return this.errors && this.errors.delivery && this.basket.delivery_selected;
        }
    },

    watch: {
        'basket.delivery_instructions': {
            immediate: true,
            handler(newVal) {
                this.localDeliveryInstructions = newVal || '';
            }
        },
        localDeliveryInstructions(newVal) {
            if (newVal !== (this.basket.delivery_instructions || '')) {
                this.$emit('update-field', { path: 'delivery_instructions', value: newVal });
            }
        }
    },

    methods: {
        onDeliveryChange(value) {
            this.$emit('update-delivery', value);
        }
    }
};
</script>

<style lang="less" scoped>
.deliveryInstructionsWrapper {
    padding-top: 15px;
}
</style>
