<script setup>
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';

import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModelPopup from './FormModelPopup.vue';

const emit = defineEmits(['onDataSaved']);

const { t } = useI18n();

const provinceFormData = reactive({
    name: null,
    autonomyFk: null,
});
const $props = defineProps({
    countryFk: {
        type: Number,
        default: null,
    },
    provinces: {
        type: Array,
        default: () => [],
    },
});
const autonomiesOptions = ref([]);

const onDataSaved = (dataSaved, requestResponse) => {
    requestResponse.autonomy = autonomiesOptions.value.find(
        (autonomy) => autonomy.id == requestResponse.autonomyFk
    );
    emit('onDataSaved', dataSaved, requestResponse);
};
</script>

<template>
    <FetchData
        @on-fetch="(data) => (autonomiesOptions = data)"
        auto-load
        :filter="{
            where: {
                countryFk: $props.countryFk,
            },
        }"
        url="Autonomies/location"
        :sort-by="['name ASC']"
        :limit="30"
    />
    <FormModelPopup
        :title="t('New province')"
        :subtitle="t('Please, ensure you put the correct data!')"
        url-create="provinces"
        model="province"
        :form-initial-data="provinceFormData"
        @on-data-saved="onDataSaved"
    >
        <template #form-inputs="{ data, validate }">
            <VnRow>
                <VnInput
                    :label="t('Name')"
                    v-model="data.name"
                    :rules="validate('province.name')"
                />
                <VnSelect
                    :label="t('Autonomy')"
                    :options="autonomiesOptions"
                    hide-selected
                    option-label="name"
                    option-value="id"
                    v-model="data.autonomyFk"
                    :rules="validate('province.autonomyFk')"
                >
                    <template #option="{ itemProps, opt }">
                        <QItem v-bind="itemProps">
                            <QItemSection>
                                <QItemLabel>{{ opt.name }}</QItemLabel>
                                <QItemLabel caption> {{ opt.country.name }} </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
            </VnRow>
        </template>
    </FormModelPopup>
</template>

<i18n>
es:
    New province: Nueva provincia
    Please, ensure you put the correct data!: ¡Por favor, asegúrese de poner los datos correctos!
    Name: Nombre
    Autonomy: Autonomía
</i18n>
