<template>
    <div class="row">
        <div class="col">
            <div class="row m-b-15" v-if="defaultAddress">
                <div class="col">
                    <div class="row" v-if="!createAddress">
                        <div class="col">
                            <div class="row m-b-10" v-if="billingAddress.length > 0">
                                <div class="col">
                                    <div class="row m-l-0 m-r-0 m-b-5">
                                        <div class="col-auto p-l-0">
                                            <div class="row align-items-center justify-content-center">
                                                <div class="col-auto">
                                                    <div class="font-heading fs-10 muted all-caps">Address Book</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col">
                                            <div class="row">
                                                <div class="col">
                                                    <div class="btn btn-xs btn-default bg-transparent text-master btn-block text-left b-rad-none p-t-0 p-b-0 p-l-15 p-r-15" @click="addressDropdownLaunch.status = !addressDropdownLaunch.status">
                                                        <div class="row">
                                                            <div class="col p-t-10 p-b-5 ">
                                                                <div class="row">
                                                                    <div class="col">
                                                                        <div class="font-heading bold lh-15" v-if="selectedAddress">
                                                                            {{ selectedAddress.street_one }}{{ selectedAddress.street_two }}, {{ selectedAddress.district?.name }} {{ selectedAddress.post_code }} {{ selectedAddress.state?.name }}, {{ selectedAddress.country?.name }}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="col-auto b-l b-grey ">
                                                                <div class="row h-100 align-items-center">
                                                                    <div class="col">
                                                                        <i class="fa text-primary" :class="[{'fa-angle-down': !addressDropdownLaunch.status}, {'fa-angle-up': addressDropdownLaunch.status}]"></i>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="relative w-100">
                                                        <div class="absolute w-100 b-l b-b b-r b-grey" :class="[{'hide': !addressDropdownLaunch.status}]" style="top: 100%; right: 0; z-index: 1;">
                                                            <div class="row text-left no-margin bg-white">
                                                                <div class="col no-padding">
                                                                    <div class="row no-margin" v-for="addressItem in billingAddress" :key="addressItem.id">
                                                                        <div class="col b-b b-grey p-t-10 p-b-10 pointer" :class="[{'bg-master-lightest': selectedAddress?.id === addressItem.id}, {'text-master': selectedAddress?.id === addressItem.id}]" @click="updateAddress(addressItem)">
                                                                            <div class="row align-items-center justify-content-center">
                                                                                <div class="col">
                                                                                    <div class="row">
                                                                                        <div class="col">
                                                                                            <div class="font-heading bold lh-15 fs-10">
                                                                                                {{ addressItem.street_one }} {{ addressItem.street_two }}, {{ addressItem.district?.name }} {{ addressItem.post_code }} {{ addressItem.state?.name }}, {{ addressItem.country?.name }}
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row parentContainer">
                        <div class="col">
                            <div class="row" v-show="!createAddress">
                                <div class="col">
                                    <button class="btn btn-xs btn-outline-primary b-rad-none" @click="createAddress = !createAddress">
                                        <i class="fa fa-plus m-r-5"></i>
                                        Add New Address
                                    </button>
                                </div>
                            </div>
                            <div class="row" v-show="createAddress">
                                <div class="col">
                                    <address-form-component 
                                        :id="props.company_id" 
                                        :type="2" 
                                        @createdAddress="updateAddress" 
                                        @close="createAddress = !createAddress"
                                    />
                                    <p class="link text-complete text-underline pointer text-center" @click="createAddress = false">Select from address book</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" v-if="selectedAddress">
                <div class="col">
                    <set-default-billing-address-component 
                        :section="section" 
                        :data="selectedAddress" 
                        v-if="defaultAddress && selectedAddress.id !== defaultAddress.id" 
                        @updateBillingAddress="updateBillingAddress"
                    />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useQueueStore } from '@/stores/queue';
import route from '@/general/functions/router';

interface Address {
    id: number;
    street_one: string;
    street_two: string;
    post_code: string;
    billing: number;
    district: { name: string };
    state: { name: string };
    country: { name: string };
}

interface Props {
    company_id?: number;
}

const props = withDefaults(defineProps<Props>(), {
    company_id: 1
});

const emit = defineEmits(['updateDefaultAddress']);

const section = ref('addressSelectionSection');
const billingAddress = ref<Address[]>([]);
const createAddress = ref(false);
const addressDropdownLaunch = ref({ status: false });
const selectedAddress = ref<Address | null>(null);

const queueStore = useQueueStore();
const { submit } = useFormHandler({ section: section.value });

const pendingQueue = computed(() => {
    return queueStore.isInCompleteQueue(section.value);
});

const defaultAddress = computed(() => {
    const foundDefault = billingAddress.value.find(item => item.billing === 1);
    if (!selectedAddress.value && foundDefault) {
        selectedAddress.value = foundDefault;
    }
    return foundDefault;
});

watch(pendingQueue, (inComplete) => {
    if (inComplete) {
        fetchBillingAddress();
    }
});

const fetchBillingAddress = () => {
    const url = (window as any).route('api.address.list') + '?filters={%22company_id%22:' + props.company_id + '}';
    submit(url, 'get', section.value, false, false, null, {
        successHandler: (result: any) => {
            billingAddress.value = result.payload.data;
        }
    });
};

const updateAddress = (address: Address) => {
    addressDropdownLaunch.value.status = false;
    selectedAddress.value = address;
    createAddress.value = false;
};

const updateBillingAddress = (addressId: number) => {
    emit('updateDefaultAddress', addressId);
};

onMounted(() => {
    queueStore.updateListQueue({ name: section.value });
    fetchBillingAddress();
});
</script>