<script setup>
import CreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue';
import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import { useI18n } from 'vue-i18n';
import { ref } from 'vue';
const { t } = useI18n();
const emit = defineEmits(['update:model-value', 'update:options']);

const props = defineProps({
    location: {
        type: Object,
        default: null,
    },
});

const locationProperties = [
    'postcode',
    (obj) =>
        obj.city
            ? `${obj.city}${obj.province?.name ? `(${obj.province.name})` : ''}`
            : null,
    (obj) => obj.country?.name,
];

const formatLocation = (obj, properties) => {
    const parts = properties.map((prop) => {
        if (typeof prop === 'string') {
            return obj[prop];
        } else if (typeof prop === 'function') {
            return prop(obj);
        }
        return null;
    });

    const filteredParts = parts.filter(
        (part) => part !== null && part !== undefined && part !== ''
    );

    return filteredParts.join(', ');
};

const modelValue = ref(
    props.location ? formatLocation(props.location, locationProperties) : null
);

function showLabel(data) {
    const dataProperties = [
        'code',
        (obj) => (obj.town ? `${obj.town}(${obj.province})` : null),
        'country',
    ];
    return formatLocation(data, dataProperties);
}

const handleModelValue = (data) => {
    emit('update:model-value', data);
};
</script>
<template>
    <VnSelectDialog
        v-model="modelValue"
        option-filter-value="search"
        :option-label="
            (opt) => (typeof modelValue === 'string' ? modelValue : showLabel(opt))
        "
        url="Postcodes/filter"
        @update:model-value="handleModelValue"
        :use-like="false"
        :label="t('Location')"
        :placeholder="t('search_by_postalcode')"
        :input-debounce="300"
        :class="{ required: $attrs.required }"
        v-bind="$attrs"
        clearable
        :emit-value="false"
        :tooltip="t('Create new location')"
    >
        <template #form>
            <CreateNewPostcode
                @on-data-saved="
                    (newValue) => {
                        modelValue = newValue;
                        emit('update:model-value', newValue);
                    }
                "
            />
        </template>
        <template #option="{ itemProps, opt }">
            <QItem v-bind="itemProps">
                <QItemSection v-if="opt.code">
                    <QItemLabel>{{ opt.code }}</QItemLabel>
                    <QItemLabel caption>{{ showLabel(opt) }}</QItemLabel>
                </QItemSection>
            </QItem>
        </template>
    </VnSelectDialog>
</template>
<style lang="scss" scoped>
.add-icon {
    cursor: pointer;
    background-color: $primary;
    border-radius: 50px;
}
</style>

<i18n>
en:
    search_by_postalcode: Search by postalcode, town, province or country
    Create new location: Create new location
es:
    Location: Ubicación
    Create new location: Crear nueva ubicación
    search_by_postalcode: Buscar por código postal, ciudad o país
</i18n>
