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

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,
    },
});
const autonomiesRef = ref([]);

const onDataSaved = (dataSaved, requestResponse) => {
    requestResponse.autonomy = autonomiesRef.value.opts.find(
        (autonomy) => autonomy.id == requestResponse.autonomyFk
    );
    emit('onDataSaved', dataSaved, requestResponse);
};
const where = computed(() => {
    if (!$props.countryFk) {
        return {};
    }
    return { countryFk: $props.countryFk };
});
</script>

<template>
    <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')"
                    required
                    data-cy="provinceName"
                />
                <VnSelect
                    data-cy="autonomyProvince"
                    required
                    ref="autonomiesRef"
                    auto-load
                    :where="where"
                    url="Autonomies/location"
                    :sort-by="['name ASC']"
                    :limit="30"
                    :label="t('Autonomy')"
                    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>
