<script setup>
import { ref, watch } from 'vue';
import { useValidator } from 'src/composables/useValidator';
import { useI18n } from 'vue-i18n';

import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import FetchData from 'components/FetchData.vue';
import CreateNewProvinceForm from './CreateNewProvinceForm.vue';

const emit = defineEmits(['onProvinceCreated']);
const provinceFk = defineModel({ type: Number });
watch(provinceFk, async () => await provincesFetchDataRef.value.fetch());

const { validate } = useValidator();
const { t } = useI18n();

const provincesOptions = ref();
const provincesFetchDataRef = ref();

async function onProvinceCreated(_, data) {
    await provincesFetchDataRef.value.fetch();
    provinceFk.value = data.id;
    emit('onProvinceCreated', data);
}
</script>

<template>
    <FetchData
        ref="provincesFetchDataRef"
        :filter="{ include: { relation: 'country' } }"
        @on-fetch="(data) => (provincesOptions = data)"
        auto-load
        url="Provinces"
    />
    <VnSelectDialog
        :label="t('Province')"
        :options="provincesOptions"
        hide-selected
        v-model="provinceFk"
        :rules="validate && validate('postcode.provinceFk')"
        :roles-allowed-to-create="['deliveryAssistant']"
    >
        <template #option="{ itemProps, opt }">
            <QItem v-bind="itemProps">
                <QItemSection>
                    <QItemLabel>{{ opt.name }}</QItemLabel>
                    <QItemLabel caption> {{ opt.country.name }} </QItemLabel>
                </QItemSection>
            </QItem>
        </template>
        <template #form>
            <CreateNewProvinceForm @on-data-saved="onProvinceCreated" />
        </template>
    </VnSelectDialog>
</template>
<i18n>
    es:
        Province: Provincia
</i18n>
