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

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

import { useState } from 'src/composables/useState';

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

const route = useRoute();
const { t } = useI18n();
const state = useState();
const user = state.getUser();
const stateFetchDataRef = ref(null);
const statesOptions = ref([]);

const onStateFkChange = (formData) => (formData.userFk = user.value.id);
</script>
<template>
    <FetchData
        ref="stateFetchDataRef"
        url="States"
        auto-load
        @on-fetch="(data) => (statesOptions = data)"
    />
    <FormModelPopup
        :title="t('Create tracking')"
        url-create="Tickets/state"
        model="CreateTicketTracking"
        :form-initial-data="{ ticketFk: route.params.id }"
        @on-data-saved="() => emit('onRequestCreated')"
    >
        <template #form-inputs="{ data }">
            <VnRow>
                <VnSelect
                    v-model="data.stateFk"
                    :label="t('tracking.state')"
                    :options="statesOptions"
                    @update:model-value="onStateFkChange(data)"
                    hide-selected
                    option-label="name"
                    option-value="id"
                />
                <VnSelect
                    :label="t('tracking.worker')"
                    v-model="data.userFk"
                    url="Workers/search"
                    fields=" ['id', 'name']"
                    sort-by="name ASC"
                    hide-selected
                    option-label="name"
                    option-value="id"
                >
                    <template #option="{ opt, itemProps }">
                        <QItem v-bind="itemProps">
                            <QItemSection>
                                <QItemLabel>
                                    {{ opt.name }}
                                </QItemLabel>
                                <QItemLabel caption>
                                    {{ opt.nickname }}, {{ opt.code }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template></VnSelect
                >
            </VnRow>
        </template>
    </FormModelPopup>
</template>

<i18n>
    es:
        Create tracking: Crear estado
</i18n>
