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

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import FetchData from 'components/FetchData.vue';
import FormModelPopup from 'src/components/FormModelPopup.vue';
import { useVnConfirm } from 'composables/useVnConfirm';

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

const { t } = useI18n();
const { notify } = useNotify();

const paginate = ref();
const dialog = ref();
const route = useRoute();
const { openConfirmationModal } = useVnConfirm();
const routeId = computed(() => route.params.id);

const initialData = computed(() => {
    return {
        userFk: routeId.value,
        deviceProductionFk: null,
        simSerialNumber: null,
    };
});

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

function reloadData() {
    initialData.value.deviceProductionFk = null;
    initialData.value.simSerialNumber = null;
    paginate.value.fetch();
}
</script>

<template>
    <QPage class="column items-center q-pa-md centerCard">
        <FetchData
            url="workers/getAvailablePda"
            @on-fetch="(data) => (deviceProductions = data)"
            auto-load
        />
        <VnPaginate
            ref="paginate"
            data-key="WorkerPda"
            url="DeviceProductionUsers"
            :filter="{ where: { userFk: routeId } }"
            order="id"
            auto-load
        >
            <template #body="{ rows }">
                <QCard
                    flat
                    bordered
                    :key="row.id"
                    v-for="row of rows"
                    class="card q-px-md q-mb-sm container"
                >
                    <VnRow>
                        <VnInput
                            :label="t('worker.pda.currentPDA')"
                            :model-value="row?.deviceProductionFk"
                            disable
                        />
                        <VnInput
                            :label="t('Model')"
                            :model-value="row?.deviceProduction?.modelFk"
                            disable
                        />
                        <VnInput
                            :label="t('Serial number')"
                            :model-value="row?.deviceProduction?.serialNumber"
                            disable
                        />
                        <VnInput
                            :label="t('Current SIM')"
                            :model-value="row?.simSerialNumber"
                            disable
                        />
                        <QBtn
                            flat
                            icon="delete"
                            color="primary"
                            class="btn-delete"
                            @click="
                                openConfirmationModal(
                                    t(`Remove PDA`),
                                    t('Do you want to remove this PDA?'),
                                    () => deallocatePDA(row.deviceProductionFk)
                                )
                            "
                        >
                            <QTooltip>
                                {{ t('worker.pda.removePDA') }}
                            </QTooltip>
                        </QBtn>
                    </VnRow>
                </QCard>
            </template>
        </VnPaginate>
        <QPageSticky :offset="[18, 18]">
            <QBtn @click.stop="dialog.show()" color="primary" fab icon="add" shortcut="+">
                <QDialog ref="dialog">
                    <FormModelPopup
                        :title="t('Add new device')"
                        url-create="DeviceProductionUsers"
                        model="DeviceProductionUser"
                        :form-initial-data="initialData"
                        @on-data-saved="reloadData()"
                    >
                        <template #form-inputs="{ data }">
                            <VnRow>
                                <VnSelect
                                    :label="t('worker.pda.newPDA')"
                                    v-model="data.deviceProductionFk"
                                    :options="deviceProductions"
                                    option-label="id"
                                    option-value="id"
                                    id="deviceProductionFk"
                                    hide-selected
                                >
                                    <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>
                                </VnSelect>
                                <VnInput
                                    v-model="data.simSerialNumber"
                                    :label="t('SIM serial number')"
                                    id="simSerialNumber"
                                    use-input
                                />
                            </VnRow>
                        </template>
                    </FormModelPopup>
                </QDialog>
            </QBtn>
            <QTooltip>
                {{ t('globals.new') }}
            </QTooltip>
        </QPageSticky>
    </QPage>
</template>
<style lang="scss" scoped>
.btn-delete {
    max-width: 4%;
    margin-top: 30px;
}
</style>
<i18n>
es:
    Model: Modelo
    Serial number: Número de serie
    Current SIM: SIM actual
    Add new device: Añadir nuevo dispositivo
    PDA deallocated: PDA desasignada
    Remove PDA: Eliminar PDA
    Do you want to remove this PDA?: ¿Desea eliminar este PDA?
    You can only have one PDA: Solo puedes tener un PDA si no eres autonomo
    This PDA is already assigned to another user: Este PDA ya está asignado a otro usuario
</i18n>
