<script setup>
import { onBeforeMount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import axios from 'axios';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();

const addresses = ref([]);
const client = ref(null);

const addressFilter = {
    fields: [
        'id',
        'isDefaultAddress',
        'isActive',
        'nickname',
        'street',
        'city',
        'provinceFk',
        'phone',
        'mobile',
        'isEqualizated',
        'isLogifloraAllowed',
        'postalCode',
    ],
    order: ['isDefaultAddress DESC', 'isActive DESC', 'nickname ASC'],
    include: [
        {
            relation: 'observations',
            scope: {
                include: 'observationType',
            },
        },
        {
            relation: 'province',
            scope: {
                fields: ['id', 'name', 'countryFk'],
                include: [
                    {
                        relation: 'country',
                        scope: { fields: ['id', 'name'] },
                    },
                ],
            },
        },
    ],
};

onBeforeMount(() => {
    const { id } = route.params;
    getAddressesData(id);
    getClientData(id);
});

watch(
    () => route.params.id,
    (newValue) => {
        if (!newValue) return;
        getAddressesData(newValue);
        getClientData(newValue);
    }
);

const getAddressesData = async (id) => {
    try {
        const { data } = await axios.get(`Clients/${id}/addresses`, {
            params: { filter: JSON.stringify(addressFilter) },
        });
        addresses.value = data;
        sortAddresses();
    } catch (error) {
        return error;
    }
};

const getClientData = async (id) => {
    try {
        const { data } = await axios.get(`Clients/${id}`);
        client.value = data;
    } catch (error) {
        return error;
    }
};

const isDefaultAddress = (address) => {
    return client?.value?.defaultAddressFk === address.id ? 1 : 0;
};

const setDefault = (address) => {
    const url = `Clients/${route.params.id}`;
    const payload = { defaultAddressFk: address.id };
    axios.patch(url, payload).then((res) => {
        if (res.data) {
            client.value.defaultAddressFk = res.data.defaultAddressFk;
            sortAddresses();
        }
    });
};

const sortAddresses = () => {
    if (!client.value || !addresses.value) return;
    addresses.value = addresses.value.sort((a, b) => {
        return isDefaultAddress(b) - isDefaultAddress(a);
    });
};

const toCustomerAddressCreate = () => {
    router.push({ name: 'CustomerAddressCreate' });
};

const toCustomerAddressEdit = (addressId) => {
    router.push({
        name: 'CustomerAddressEdit',
        params: {
            id: route.params.id,
            addressId,
        },
    });
};
</script>

<template>
    <div class="full-width flex justify-center">
        <QCard class="card-width q-pa-lg" v-if="addresses.length">
            <QCardSection>
                <div
                    v-for="(item, index) in addresses"
                    :key="index"
                    class="address-card"
                    :class="{
                        'q-mb-md': index < addresses.length - 1,
                        'item-disabled': !item.isActive,
                    }"
                    @click="toCustomerAddressEdit(item.id)"
                >
                    <div class="q-ml-xs q-mr-md flex items-center">
                        <QIcon
                            :style="{
                                'font-variation-settings': `'FILL' ${isDefaultAddress(
                                    item
                                )}`,
                            }"
                            color="primary"
                            name="star"
                            size="md"
                            @click.stop="!isDefaultAddress(item) && setDefault(item)"
                        >
                            <QTooltip>
                                {{
                                    t(
                                        isDefaultAddress(item)
                                            ? 'Default address'
                                            : 'Set as default'
                                    )
                                }}
                            </QTooltip>
                        </QIcon>
                    </div>
                    <div>
                        <div class="text-weight-bold q-mb-sm">
                            {{ item.nickname }} - #{{ item.id }}
                        </div>
                        <div>{{ item.street }}</div>
                        <div>
                            {{ item.postalCode }} - {{ item.city }},
                            {{ item.province.name }}
                        </div>
                        <div>
                            {{ item.phone }}
                            <span v-if="item.mobile"
                                >,
                                {{ item.mobile }}
                            </span>
                        </div>
                        <div class="flex">
                            <QCheckbox
                                :label="t('Is equalizated')"
                                v-model="item.isEqualizated"
                                class="q-mr-lg"
                                disable
                            />
                            <QCheckbox
                                :label="t('Is logiflora allowed')"
                                v-model="item.isLogifloraAllowed"
                                disable
                            />
                        </div>
                    </div>

                    <QSeparator
                        class="q-mx-lg"
                        v-if="item.observations.length"
                        vertical
                    />

                    <div v-if="item.observations.length">
                        <div
                            :key="obIndex"
                            class="flex q-mb-sm"
                            v-for="(observation, obIndex) in item.observations"
                        >
                            <div class="text-weight-bold q-mr-sm">
                                {{ observation.observationType.description }}:
                            </div>
                            <div>{{ observation.description }}</div>
                        </div>
                    </div>
                </div>
            </QCardSection>
        </QCard>
    </div>

    <QPageSticky :offset="[18, 18]">
        <QBtn
            @click.stop="toCustomerAddressCreate()"
            color="primary"
            fab
            icon="add"
            shortcut="+"
        />
        <QTooltip>
            {{ t('New consignee') }}
        </QTooltip>
    </QPageSticky>
</template>

<style lang="scss" scoped>
.address-card {
    border: 2px solid var(--vn-light-gray);
    border-radius: 10px;
    padding: 10px;
    display: flex;
    cursor: pointer;

    &:hover {
        background-color: var(--vn-accent-color);
    }
}

.item-disabled {
    opacity: 0.6;
}
</style>

<i18n>
es:
    Is equalizated: Recargo de equivalencia
    Is logiflora allowed: Compra directa en Holanda
    New consignee: Nuevo consignatario
    Default address: Consignatario predeterminado
    Set as default: Establecer como predeterminado
</i18n>
