<script setup>
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import CardDescriptor from 'src/components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import VnLinkPhone from 'src/components/ui/VnLinkPhone.vue';
import WorkerChangePasswordForm from 'src/pages/Worker/Card/WorkerChangePasswordForm.vue';
import useCardDescription from 'src/composables/useCardDescription';
import { useState } from 'src/composables/useState';
import axios from 'axios';
import VnImg from 'src/components/ui/VnImg.vue';

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const route = useRoute();
const { t } = useI18n();
const state = useState();
const user = state.getUser();
const changePasswordFormDialog = ref(null);
const cardDescriptorRef = ref(null);

const entityId = computed(() => {
    return $props.id || route.params.id;
});

const worker = ref();
const workerExcluded = ref(false);
const filter = {
    include: [
        {
            relation: 'user',
            scope: {
                fields: ['email', 'name', 'nickname'],
            },
        },
        {
            relation: 'department',
            scope: {
                include: [
                    {
                        relation: 'department',
                    },
                ],
            },
        },
        {
            relation: 'sip',
        },
    ],
};

const sip = ref(null);
watch(
    () => [worker.value?.sip?.extension, state.get('extension')],
    ([newWorkerSip, newStateExtension], [oldWorkerSip, oldStateExtension]) => {
        if (newStateExtension !== oldStateExtension || sip.value === oldStateExtension) {
            sip.value = newStateExtension;
        } else if (newWorkerSip !== oldWorkerSip && sip.value !== newStateExtension) {
            sip.value = newWorkerSip;
        }
    }
);

const data = ref(useCardDescription());
const setData = (entity) => {
    if (!entity) return;
    data.value = useCardDescription(entity.user?.nickname, entity.id);
};

const openChangePasswordForm = () => changePasswordFormDialog.value.show();

const getIsExcluded = async () => {
    try {
        const { data } = await axios.get(
            `WorkerDisableExcludeds/${entityId.value}/exists`
        );
        if (!data) return;
        workerExcluded.value = data.exists;
    } catch (err) {
        console.error('Error getting worker excluded: ', err);
    }
};

const handleExcluded = async () => {
    if (workerExcluded.value)
        await axios.delete(`WorkerDisableExcludeds/${entityId.value}`);
    else
        await axios.post(`WorkerDisableExcludeds`, {
            workerFk: entityId.value,
            dated: new Date(),
        });

    workerExcluded.value = !workerExcluded.value;
};

const refetch = async () => await cardDescriptorRef.value.getData();
</script>
<template>
    <CardDescriptor
        ref="cardDescriptorRef"
        module="Worker"
        data-key="workerData"
        :url="`Workers/${entityId}`"
        :filter="filter"
        :title="data.title"
        :subtitle="data.subtitle"
        :summary="$attrs"
        @on-fetch="
            (data) => {
                worker = data;
                setData(data);
                getIsExcluded();
            }
        "
    >
        <template #menu="{}">
            <QItem v-ripple clickable @click="handleExcluded()">
                <QItemSection>
                    {{
                        workerExcluded
                            ? t('Click to allow the user to be disabled')
                            : t('Click to exclude the user from getting disabled')
                    }}
                </QItemSection>
            </QItem>
            <QItem
                v-if="!worker.user.emailVerified && user.id != worker.id"
                v-ripple
                clickable
                @click="openChangePasswordForm()"
            >
                <QItemSection>
                    {{ t('Change password') }}
                    <QDialog ref="changePasswordFormDialog">
                        <WorkerChangePasswordForm @on-submit="refetch()" :id="entityId" />
                    </QDialog>
                </QItemSection>
            </QItem>
        </template>
        <template #before>
            <VnImg :id="entityId" collection="user" size="160x160" class="photo">
                <template #error>
                    <div
                        class="absolute-full picture text-center q-pa-md flex flex-center"
                    >
                        <div>
                            <div class="text-grey-5" style="opacity: 0.4; font-size: 5vh">
                                <QIcon name="vn:claims" />
                            </div>
                            <div class="text-grey-5" style="opacity: 0.4">
                                {{ t('worker.imageNotFound') }}
                            </div>
                        </div>
                    </div>
                </template>
            </VnImg>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('worker.card.name')" :value="entity.user?.nickname" />
            <VnLv :label="t('worker.card.email')" :value="entity.user?.email" copy />
            <VnLv
                :label="t('worker.list.department')"
                :value="entity.department ? entity.department.department.name : null"
            />
            <VnLv :value="entity.phone">
                <template #label>
                    {{ t('worker.card.phone') }}
                    <VnLinkPhone :phone-number="entity.phone" />
                </template>
            </VnLv>
            <VnLv :value="sip">
                <template #label>
                    {{ t('worker.summary.sipExtension') }}
                    <VnLinkPhone v-if="sip" :phone-number="sip" />
                </template>
            </VnLv>
        </template>
    </CardDescriptor>
</template>

<style lang="scss" scoped>
.photo {
    height: 256px;
}
</style>

<i18n>
es:
    Click to allow the user to be disabled: Marcar para deshabilitar
    Click to exclude the user from getting disabled: Marcar para no deshabilitar
    Change password: Cambiar contraseña
</i18n>
