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

const { validate } = useValidator();
const { t } = useI18n();
const filter = ref({
    include: { relation: 'country' },
    where: {
        countryFk: $props.countryFk,
    },
});
const provincesOptions = ref($props.provinces);
const provincesFetchDataRef = ref();
provinceFk.value = $props.provinceSelected;
if (!$props.countryFk) {
    filter.value.where = {};
}
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;
}

watch(
    () => $props.countryFk,
    async () => {
        if ($props.countryFk) {
            filter.value.where.countryFk = $props.countryFk;
        } else filter.value.where = {};
        await provincesFetchDataRef.value.fetch({});
        emit('onProvinceFetched', provincesOptions.value);
    }
);
</script>

<template>
    <FetchData
        ref="provincesFetchDataRef"
        :filter="filter"
        @on-fetch="handleProvinces"
        url="Provinces"
        auto-load
    />
    <VnSelectDialog
        data-cy="locationProvince"
        :label="t('Province')"
        :options="provincesOptions"
        :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>
