<script setup>
import { onMounted, useSlots, computed, ref, toRef, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import SkeletonDescriptor from 'components/ui/SkeletonDescriptor.vue';

const props = defineProps({
    id: {
        type: Number,
        required: true,
    },
    module: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: false,
        default: '',
    },
});

const slots = useSlots();
const { t } = useI18n();

onMounted(async () => {
    await fetch();
});

const entity = ref();
const entityId = toRef(props, 'id');
const description = computed(() => {
    return props.description || entity.value.name;
});

async function fetch() {
    const { data } = await axios.get(`Clients/${entityId.value}/getCard`);
    entity.value = data;
}

watch(entityId, async () => {
    entity.value = null;
    await fetch();
});
</script>

<template>
    <div class="descriptor">
        <div class="header bg-primary q-pa-sm">
            <router-link :to="{ name: `${module}List` }">
                <q-btn round flat dense size="md" icon="view_list" color="white">
                    <q-tooltip>{{ t('components.cardDescriptor.mainList') }}</q-tooltip>
                </q-btn>
            </router-link>
            <router-link :to="{ name: `${module}Summary`, params: { id: entityId } }">
                <q-btn round flat dense size="md" icon="launch" color="white">
                    <q-tooltip>{{ t('components.cardDescriptor.summary') }}</q-tooltip>
                </q-btn>
            </router-link>

            <q-btn v-if="slots.menu" size="md" icon="more_vert" color="white" round flat dense>
                <q-tooltip>{{ t('components.cardDescriptor.moreOptions') }}</q-tooltip>
                <q-menu>
                    <q-list>
                        <slot name="menu" />
                    </q-list>
                </q-menu>
            </q-btn>
        </div>
        <div v-if="entity" class="body q-py-sm">
            <q-list>
                <q-item-label header class="ellipsis text-h5" :lines="1">
                    {{ description }}
                    <q-tooltip>{{ description }}</q-tooltip>
                </q-item-label>
                <q-item dense>
                    <q-item-label class="text-subtitle2" caption>#{{ entity.id }}</q-item-label>
                </q-item>
            </q-list>
            <slot name="body" :entity="entity" />
        </div>

        <!-- Skeleton -->
        <skeleton-descriptor v-if="!entity" />
    </div>
</template>

<style lang="scss">
.body {
    .q-card__actions {
        justify-content: center;
    }
    .text-h5 {
        padding-top: 5px;
        padding-bottom: 5px;
    }
}
</style>

<style lang="scss" scoped>
.descriptor {
    width: 256px;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: stretch;
    }
}
</style>
