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

const props = defineProps({
    dataKey: { type: String, required: true },
    baseUrl: { type: String, default: undefined },
    customUrl: { type: String, default: undefined },
    filter: { type: Object, default: () => {} },
    userFilter: { type: Object, default: () => {} },
    descriptor: { type: Object, required: true },
    filterPanel: { type: Object, default: undefined },
    searchDataKey: { type: String, default: undefined },
    searchbarProps: { type: Object, default: undefined },
    redirectOnError: { type: Boolean, default: false },
});

const stateStore = useStateStore();
const route = useRoute();
const router = useRouter();
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,
    userFilter: props.userFilter,
});

onBeforeMount(async () => {
    try {
        if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
        await arrayData.fetch({ append: false, updateRouter: false });
    } catch {
        const { matched: matches } = router.currentRoute.value;
        const { path } = matches.at(-1);
        router.push({ path: path.replace(/:id.*/, '') });
    }
});

if (props.baseUrl) {
    onBeforeRouteUpdate(async (to, from) => {
        if (to.params.id !== from.params.id) {
            arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
            await arrayData.fetch({ append: false, updateRouter: false });
        }
    });
}
</script>
<template>
    <Teleport to="#left-panel" v-if="stateStore.isHeaderMounted()">
        <component :is="descriptor" />
        <QSeparator />
        <LeftMenu source="card" />
    </Teleport>
    <VnSubToolbar />
    <div :class="[useCardSize(), $attrs.class]">
        <RouterView :key="route.path" />
    </div>
</template>
