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

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

const { t } = useI18n();
const router = useRouter();

const newItemTypeForm = reactive({});

const categoriesOptions = ref([]);
const temperaturesOptions = ref([]);

const redirectToItemTypeBasicData = (_, { id }) => {
    router.push({ name: 'ItemTypeBasicData', params: { id } });
};
</script>

<template>
    <FetchData
        url="ItemCategories"
        @on-fetch="(data) => (categoriesOptions = data)"
        :filter="{ order: 'name ASC', fields: ['id', 'name'] }"
        auto-load
    />
    <FetchData
        url="Temperatures"
        @on-fetch="(data) => (temperaturesOptions = data)"
        :filter="{ order: 'name ASC', fields: ['code', 'name'] }"
        auto-load
    />
    <QPage>
        <VnSubToolbar />
        <FormModel
            url-create="ItemTypes"
            model="itemTypeCreate"
            :form-initial-data="newItemTypeForm"
            observe-form-changes
            @on-data-saved="redirectToItemTypeBasicData"
        >
            <template #form="{ data }">
                <VnRow>
                    <VnInput v-model="data.code" :label="t('itemType.shared.code')" />
                    <VnInput v-model="data.name" :label="t('itemType.shared.name')" />
                </VnRow>
                <VnRow>
                    <VnSelect
                        v-model="data.workerFk"
                        :label="t('itemType.shared.worker')"
                        url="Workers"
                        sort-by="firstName ASC"
                        :fields="['id', 'firstName']"
                        option-value="id"
                        option-label="firstName"
                        hide-selected
                    />
                    <VnSelect
                        v-model="data.categoryFk"
                        :label="t('itemType.shared.category')"
                        :options="categoriesOptions"
                        option-value="id"
                        option-label="name"
                        hide-selected
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        v-model="data.temperatureFk"
                        :label="t('itemType.shared.temperature')"
                        :options="temperaturesOptions"
                        option-value="code"
                        option-label="name"
                        hide-selected
                    />
                </VnRow>
            </template>
        </FormModel>
    </QPage>
</template>
