<script setup>
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { onMounted, ref, computed } from 'vue';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import { useRole } from 'src/composables/useRole';

const route = useRoute();
const { t } = useI18n();
const { notify } = useNotify();
const { hasAny } = useRole();

const fetchCurrentDeviceRef = ref(null);
const deviceProductionsFilter = {
    fields: ['id', 'serialNumber', 'modelFk'],
    where: { stateFk: 'idle' },
    order: 'id',
};
const deviceProductionsOptions = ref([]);
const newPDA = ref({});
const currentPDA = ref(null);

const isAllowedToEdit = computed(() => hasAny(['hr', 'productionAssi']));

const setCurrentPDA = (data) => {
    currentPDA.value = data;
    currentPDA.value.description = `ID: ${currentPDA.value.deviceProductionFk} ${t(
        'worker.pda.model'
    )}: ${currentPDA.value.deviceProduction.modelFk} ${t('worker.pda.serialNumber')}: ${
        currentPDA.value.deviceProduction.serialNumber
    }`;
};

const deallocatePDA = async (data) => {
    try {
        await axios.post(`Workers/${route.params.id}/deallocatePDA`, {
            pda: currentPDA.value.deviceProductionFk,
        });
        data.pda = null;
        currentPDA.value = null;
        await fetchCurrentDeviceRef.value.fetch();
        notify(t('PDA deallocated'), 'positive');
    } catch (err) {
        console.error('Error deallocating PDA');
    }
};

onMounted(async () => await fetchCurrentDeviceRef.value.fetch());
</script>

<template>
    <FetchData
        url="DeviceProductions"
        :filter="deviceProductionsFilter"
        auto-load
        @on-fetch="(data) => (deviceProductionsOptions = data)"
    />
    <FetchData
        ref="fetchCurrentDeviceRef"
        url="DeviceProductionUsers"
        :filter="{
            where: { userFk: route.params.id },
            include: { relation: 'deviceProduction' },
        }"
        auto-load
        @on-fetch="(data) => setCurrentPDA(data[0])"
    />
    <QPage class="column items-center q-pa-md">
        <FormModel
            url="DeviceProductionUsers"
            :url-create="`Workers/${route.params.id}/allocatePDA`"
            model="DeviceProductionUser"
            :form-initial-data="newPDA"
            auto-load
            :default-buttons="{ save: { label: 'globals.assign', color: 'primary' } }"
            @on-data-saved="(_, data) => setCurrentPDA(data)"
        >
            <template #form="{ data }">
                <QField
                    v-if="currentPDA && currentPDA.description"
                    :label="t('worker.pda.currentPDA')"
                    :model-value="currentPDA.description"
                    :editable="false"
                    class="full-width"
                >
                    <template #control>
                        <div tabindex="0">
                            {{ currentPDA.description }}
                        </div>
                    </template>
                    <template v-if="isAllowedToEdit" #append>
                        <QIcon
                            name="delete"
                            size="sm"
                            class="cursor-pointer"
                            color="primary"
                            @click="deallocatePDA(data)"
                        >
                            <QTooltip>
                                {{ t('worker.pda.removePDA') }}
                            </QTooltip>
                        </QIcon>
                    </template>
                </QField>

                <VnSelectFilter
                    v-else
                    :label="t('worker.pda.newPDA')"
                    v-model="data.pda"
                    :options="deviceProductionsOptions"
                    option-label="serialNumber"
                    option-value="id"
                    hide-selected
                    :disable="!isAllowedToEdit"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel>ID: {{ scope.opt?.id }}</QItemLabel>
                                <QItemLabel caption>
                                    {{ scope.opt?.modelFk }},
                                    {{ scope.opt?.serialNumber }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelectFilter>
            </template>
        </FormModel>
    </QPage>
</template>

<i18n>
es:
    PDA deallocated: PDA desasignada
</i18n>
