<template>
    <div class="billingAddress">
        <!-- Country -->
        <div class="row">
            <label for="billingCountry">
                Country<sup>*</sup>
            </label>
            <div class="inputWrap">
                <chosen
                    :options="countries"
                    placeholder="Select country"
                    :value="basket.address.billing.country"
                    @input="onCountryChange"
                    class="selectCountry"
                    id="billingCountry"
                    name="billing_country"
                />
            </div>
        </div>

        <!-- Phone Number -->
        <div
            class="row"
            :class="{
                'errorWrap showError': hasError('info.contact_no') || hasError('info.phone_prefix')
            }"
        >
            <label for="phoneNo">
                Phone number<sup>*</sup>
            </label>
            <div class="inputWrap">
                <input
                    maxlength="20"
                    type="tel"
                    name="cardholder_phone_number"
                    id="phoneNo"
                    @focus="clearError('errors.info.contact_no')"
                    :value="basket.info.contact_no"
                    @input="updateField('info.contact_no', $event.target.value)"
                    class="text"
                />
                <input
                    type="hidden"
                    name="cardholder_phone_prefix"
                    id="phonePrefix"
                    :value="basket.info.phone_prefix"
                    @focus="clearError('errors.info.phone_prefix')"
                    class="text prefix"
                    autocomplete="off"
                    readonly
                />
            </div>
            <div class="validationMessage" v-if="hasError('info.contact_no')">
                <span>{{ errors.info.contact_no }}</span>
            </div>
            <div class="validationMessage" v-if="hasError('info.phone_prefix')">
                <span>{{ errors.info.phone_prefix }}</span>
            </div>
        </div>

        <!-- Postcode Lookup (if PAF enabled) -->
        <postcode-lookup
            v-if="pafEnabled"
            type="billing"
            :address="basket.address.billing"
            :address-list="addressList"
            :selected-paf-address="pafAddress"
            :cant-find-address="cantFindAddress"
            :errors="errors"
            :paf-enabled="pafEnabled"
            :has-postcodes="hasPostcodesComputed"
            @clear-error="clearError"
            @update-field="onUpdateField"
            @trigger-paf="$emit('trigger-paf')"
            @set-paf-address="(val) => $emit('set-paf-address', val)"
            @toggle-cant-find="$emit('toggle-cant-find')"
        />

        <!-- Address Line 1 -->
        <div
            class="row"
            :class="{ 'errorWrap showError': hasError('address.billing.address1') }"
        >
            <label for="billingAddress1">
                Address Line 1<sup>*</sup>
            </label>
            <div class="inputWrap">
                <input
                    maxlength="100"
                    type="text"
                    @focus="clearError('errors.address.billing.address1')"
                    name="billing_address_line_1"
                    id="billingAddress1"
                    :value="basket.address.billing.address1"
                    @input="updateField('address.billing.address1', $event.target.value)"
                    class="text"
                />
            </div>
            <div class="validationMessage" v-if="hasError('address.billing.address1')">
                <span>{{ errors.address.billing.address1 }}</span>
            </div>
        </div>

        <!-- Address Line 2 -->
        <div
            class="row"
            :class="{ 'errorWrap showError': hasError('address.billing.address2') }"
        >
            <label for="billingAddress2">
                Address Line 2
            </label>
            <div class="inputWrap">
                <input
                    maxlength="100"
                    type="text"
                    name="billing_address_line_2"
                    id="billingAddress2"
                    @focus="clearError('errors.address.billing.address2')"
                    :value="basket.address.billing.address2"
                    @input="updateField('address.billing.address2', $event.target.value)"
                    class="text"
                />
            </div>
            <div class="validationMessage" v-if="hasError('address.billing.address2')">
                <span>{{ errors.address.billing.address2 }}</span>
            </div>
        </div>

        <!-- City -->
        <div
            class="row"
            :class="{ 'errorWrap showError': hasError('address.billing.city') }"
        >
            <label for="billingCity">
                City<sup>*</sup>
            </label>
            <div class="inputWrap">
                <input
                    maxlength="39"
                    type="text"
                    name="billing_city"
                    id="billingCity"
                    @focus="clearError('errors.address.billing.city')"
                    :value="basket.address.billing.city"
                    @input="updateField('address.billing.city', $event.target.value)"
                    class="text"
                />
            </div>
            <div class="validationMessage" v-if="hasError('address.billing.city')">
                <span>{{ errors.address.billing.city }}</span>
            </div>
        </div>

        <!-- Postcode (if PAF not enabled) -->
        <div
            v-if="!pafEnabled"
            class="row"
            :class="{ 'errorWrap showError': hasError('address.billing.postcode') }"
        >
            <label for="noPafBillingPostcode">
                Postcode/Zip<sup v-show="hasPostcodesComputed">*</sup>
            </label>
            <div class="inputWrap">
                <input
                    maxlength="10"
                    type="text"
                    name="billing_postcode"
                    id="noPafBillingPostcode"
                    @focus="clearError('errors.address.billing.postcode')"
                    :value="basket.address.billing.postcode"
                    @input="updateField('address.billing.postcode', $event.target.value)"
                    class="text"
                />
            </div>
            <div class="validationMessage" v-if="hasError('address.billing.postcode')">
                <span>{{ errors.address.billing.postcode }}</span>
            </div>
        </div>

        <!-- Country Error -->
        <div
            class="row country"
            :class="{ 'errorWrap showError': hasError('address.billing.country') }"
        >
            <div class="validationMessage" v-if="hasError('address.billing.country')">
                <span>{{ errors.address.billing.country }}</span>
            </div>
        </div>

        <!-- State (if applicable) -->
        <div
            class="row billingState"
            v-show="hasStatesComputed"
            :class="{ 'errorWrap showError': hasError('address.billing.state') }"
        >
            <label class="country" for="billingState">
                State<sup>*</sup>
            </label>
            <div class="inputWrap">
                <select
                    name="billing_state"
                    :value="basket.address.billing.state"
                    @change="onStateChange"
                    id="billingState"
                >
                    <option value="">Choose State</option>
                    <option
                        v-for="(state, key) in stateList.billing"
                        :key="key"
                        :value="key"
                    >
                        {{ state }}
                    </option>
                </select>
            </div>
            <div class="validationMessage" v-if="hasError('address.billing.state')">
                <span>{{ errors.address.billing.state }}</span>
            </div>
        </div>

        <!-- Ship to this address checkbox -->
        <div class="row alt_del checkboxRow" v-if="allowAlternateDelivery">
            <input
                type="checkbox"
                name="shipping_address"
                id="shippingAddress"
                @change="onShippingToggle"
                :checked="basket.billing_address_used === 1"
                :true-value="1"
                :false-value="0"
            />
            <label for="shippingAddress">
                Ship to this address?
            </label>
        </div>
        <input
            v-else
            type="hidden"
            name="shipping_address"
            :value="basket.billing_address_used"
        />
    </div>
</template>

<script>
import PostcodeLookup from '../shared/postcode_lookup.vue';
import errorMixin from '../shared/error_mixin.js';

export default {
    name: 'billing-address',

    mixins: [errorMixin],

    components: {
        PostcodeLookup
    },

    props: {
        basket: {
            type: Object,
            required: true
        },
        countries: {
            type: Object,
            default: () => ({})
        },
        stateList: {
            type: [Object, Array],
            default: () => ({ billing: {}, shipping: {} })
        },
        hasPostcodes: {
            type: [Object, Boolean],
            default: () => ({})
        },
        addressList: {
            type: Array,
            default: () => []
        },
        pafAddress: {
            type: String,
            default: ''
        },
        cantFindAddress: {
            type: Boolean,
            default: false
        },
        errors: {
            type: [Object, Array],
            default: () => ({})
        },
        pafEnabled: {
            type: Boolean,
            default: true
        },
        allowAlternateDelivery: {
            type: Boolean,
            default: true
        }
    },

    computed: {
        hasStatesComputed() {
            return this.stateList.billing && Object.keys(this.stateList.billing).length > 0;
        },
        hasPostcodesComputed() {
            return this.hasPostcodes && this.hasPostcodes.billing;
        }
    },

    methods: {
        clearError(path) {
            this.$emit('clear-error', path);
        },

        updateField(path, value) {
            this.$emit('update-field', { path, value });
        },

        onUpdateField({ path, value }) {
            this.$emit('update-field', { path, value });
        },

        onCountryChange(value) {
            this.updateField('address.billing.country', value);
            // Trigger store details update after country change
            this.$nextTick(() => {
                this.$emit('store-details');
            });
        },

        onStateChange(event) {
            this.updateField('address.billing.state', event.target.value);
            this.$emit('store-details');
        },

        onShippingToggle(event) {
            const value = event.target.checked ? 1 : 0;
            this.updateField('billing_address_used', value);
            this.$emit('shipping-trigger');
        }
    }
};
</script>
