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

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

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

const { t } = useI18n();
const state = useState();
const route = useRoute();
const workerPBXForm = ref();
const extension = ref(null);

const filter = {
    include: [
        {
            relation: 'sip',
        },
    ],
};

watch(
    () => route.params.id,
    () => state.set('extension', null)
);

const onFetch = (data) => {
    state.set('extension', data?.sip?.extension);
    extension.value = state.get('extension');
};

const updateModelValue = (data) => {
    state.set('extension', data);
    workerPBXForm.value.hasChanges = true;
};
</script>

<template>
    <FormModel
        ref="workerPBXForm"
        :filter="filter"
        :url="`Workers/${route.params.id}`"
        url-update="Sips"
        auto-load
        :mapper="
            () => ({
                userFk: +route.params.id,
                extension,
            })
        "
        model="DeviceProductionUser"
        @on-fetch="onFetch"
    >
        <template #form="{}">
            <VnRow>
                <VnInput
                    :label="t('worker.summary.sipExtension')"
                    v-model="extension"
                    @update:model-value="updateModelValue"
                />
            </VnRow>
        </template>
    </FormModel>
</template>
