<script setup>
import { onBeforeMount, computed, watchEffect } from 'vue';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useArrayData } from 'src/composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';
import useCardSize from 'src/composables/useCardSize';
import VnSubToolbar from '../ui/VnSubToolbar.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import LeftMenu from 'components/LeftMenu.vue';

const props = defineProps({
    dataKey: { type: String, required: true },
    baseUrl: { type: String, default: undefined },
    customUrl: { type: String, default: undefined },
    filter: { type: Object, default: () => {} },
    descriptor: { type: Object, required: true },
    searchbarDataKey: { type: String, default: undefined },
    searchbarUrl: { type: String, default: undefined },
    searchbarLabel: { type: String, default: '' },
    searchbarInfo: { type: String, default: '' },
});

const { t } = useI18n();
const stateStore = useStateStore();
const route = useRoute();
const url = computed(() => {
    if (props.baseUrl) return `${props.baseUrl}/${route.params.id}`;
    return props.customUrl;
});

const arrayData = useArrayData(props.dataKey, {
    url: url.value,
    filter: props.filter,
});

onBeforeMount(async () => {
    if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
    await arrayData.fetch({ append: false });
});

if (props.baseUrl) {
    onBeforeRouteUpdate(async (to, from) => {
        if (to.params.id !== from.params.id) {
            arrayData.store.url = `${props.baseUrl}/${route.params.id}`;
            await arrayData.fetch({ append: false });
        }
    });
}

watchEffect(() => {
    if (Array.isArray(arrayData.store.data))
        arrayData.store.data = arrayData.store.data[0];
});
</script>
<template>
    <Teleport
        to="#searchbar"
        v-if="stateStore.isHeaderMounted() && props.searchbarDataKey"
    >
        <VnSearchbar
            :data-key="props.searchbarDataKey"
            :url="props.searchbarUrl"
            :label="t(props.searchbarLabel)"
            :info="t(props.searchbarInfo)"
        />
    </Teleport>
    <QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256">
        <QScrollArea class="fit">
            <component :is="descriptor" />
            <QSeparator />
            <LeftMenu source="card" />
        </QScrollArea>
    </QDrawer>
    <QPageContainer>
        <QPage>
            <VnSubToolbar />
            <div :class="[useCardSize(), $attrs.class]">
                <RouterView />
            </div>
        </QPage>
    </QPageContainer>
</template>
