<script setup>
import { computed, ref } 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 VnChangePassword from 'src/components/common/VnChangePassword.vue';
import { useState } from 'src/composables/useState';
import axios from 'axios';
import VnImg from 'src/components/ui/VnImg.vue';
import EditPictureForm from 'components/EditPictureForm.vue';

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

const route = useRoute();
const { t } = useI18n();
const state = useState();
const user = state.getUser();
const showEditPhotoForm = ref(false);
const toggleEditPictureForm = () => {
    showEditPhotoForm.value = !showEditPhotoForm.value;
};
const entityId = computed(() => {
    return $props.id || route.params.id;
});
const workerExcluded = ref(false);

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 handlePhotoUpdated = (evt = false) => {
    image.value.reload(evt);
};
</script>
<template>
    <CardDescriptor
        ref="cardDescriptorRef"
        module="Worker"
        data-key="workerData"
        url="Workers/descriptor"
        :filter="{ where: { id: entityId } }"
        title="user.nickname"
        @on-fetch="getIsExcluded"
    >
        <template #menu="{ entity }">
            <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="!entity.user.emailVerified && user.id != entity.id"
                v-ripple
                clickable
                @click="$refs.changePassRef.show"
            >
                <QItemSection>
                    {{ t('globals.changePass') }}
                </QItemSection>
            </QItem>
        </template>
        <template #before>
            <div class="relative-position">
                <VnImg
                    ref="image"
                    :id="parseInt(entityId)"
                    collection="user"
                    resolution="520x520"
                    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
                ><QBtn
                    color="primary"
                    size="lg"
                    round
                    class="edit-photo-btn"
                    @click="toggleEditPictureForm()"
                >
                    <QIcon name="edit" size="sm" />
                    <QDialog ref="editPhotoFormDialog" v-model="showEditPhotoForm">
                        <EditPictureForm
                            collection="user"
                            :id="entityId"
                            @close-form="toggleEditPictureForm()"
                            @on-photo-uploaded="handlePhotoUpdated"
                        />
                    </QDialog>
                </QBtn>
            </div>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('worker.card.user')" :value="entity.user?.name" />
            <VnLv
                :label="t('worker.card.email')"
                :value="entity.user?.emailUser?.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="entity?.sip?.extension">
                <template #label>
                    {{ t('worker.summary.sipExtension') }}
                    <VnLinkPhone :phone-number="entity?.sip?.extension" />
                </template>
            </VnLv>
        </template>
        <template #actions="{ entity }">
            <QCardActions class="flex justify-center">
                <QBtn
                    :to="{
                        name: 'CustomerCard',
                        params: { id: entity.id },
                    }"
                    size="md"
                    icon="vn:Person"
                    color="primary"
                >
                    <QTooltip>{{ t('Go to client') }}</QTooltip>
                </QBtn>
                <QBtn
                    :to="{
                        name: 'AccountCard',
                        params: { id: entity.user.id },
                    }"
                    size="md"
                    icon="face"
                    color="primary"
                >
                    <QTooltip>{{ t('Go to user') }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </CardDescriptor>
    <VnChangePassword
        ref="changePassRef"
        :submit-fn="
            async (newPass) => {
                await axios.patch(`Workers/${$route.params.id}/setPassword`, { newPass });
            }
        "
        @on-submit="$refs.cardDescriptorRef?.getData"
    />
</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
</i18n>
