<script setup>
import { computed, onBeforeMount } 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, default: null },
    baseUrl: { type: String, default: null },
    model: { type: String, default: null },
    filter: { type: Object, default: null },
    descriptor: { type: Object, required: true },
    searchbarDataKey: { type: String, required: true },
    searchbarUrl: { type: String, required: true },
    searchbarLabel: { type: String, required: true },
    searchbarInfo: { type: String, required: true },
});

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

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

    onBeforeMount(async () => await arrayData.fetch({ append: false }));

    onBeforeRouteUpdate(async (to, from) => {
        if (!to.params.id !== from.params.id) {
            arrayData.store.url = url;
            await arrayData.fetch({ append: false });
        }
    });
}
</script>
<template>
    <Teleport to="#searchbar" v-if="stateStore.isHeaderMounted()">
        <VnSearchbar
            :data-key="props.searchbarDataKey"
            :url="props.searchbarUrl"
            :label="t(`${props.model}.searchbar.${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()">
                <RouterView />
            </div>
        </QPage>
    </QPageContainer>
</template>
