<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 $props = defineProps({
    countryFk: {
        type: Number,
        default: null,
    },
    provinceSelected: {
        type: Number,
        default: null,
    },
    provinces: {
        type: Array,
        default: () => [],
    },
});
const provinceFk = defineModel({ type: Number, default: null });

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

const provincesOptions = ref($props.provinces);
provinceFk.value = $props.provinceSelected;
const provincesFetchDataRef = ref();

async function onProvinceCreated(_, data) {
    await provincesFetchDataRef.value.fetch({ where: { countryFk: $props.countryFk } });
    provinceFk.value = data.id;
    emit('onProvinceCreated', data);
}
async function handleProvinces(data) {
    provincesOptions.value = data;
}
</script>

<template>
    <FetchData
        ref="provincesFetchDataRef"
        :filter="{
            include: { relation: 'country' },
            where: {
                countryFk: $props.countryFk,
            },
        }"
        @on-fetch="handleProvinces"
        url="Provinces"
    />
    <VnSelectDialog
        :label="t('Province')"
        :options="$props.provinces"
        :tooltip="t('Create province')"
        hide-selected
        v-model="provinceFk"
        :rules="validate && validate('postcode.provinceFk')"
        :acls="[{ model: 'Province', props: '*', accessType: 'WRITE' }]"
    >
        <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
                :country-fk="$props.countryFk"
                @on-data-saved="onProvinceCreated"
            />
        </template>
    </VnSelectDialog>
</template>
<i18n>
    es:
        Province: Provincia
        Create province: Crear provincia
</i18n>
