<script setup>
import RightMenu from './RightMenu.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue';
import { onBeforeMount, computed, ref } from 'vue';
import { useArrayData } from 'src/composables/useArrayData';
import { useRoute } from 'vue-router';
import { useHasContent } from 'src/composables/useHasContent';

const $props = defineProps({
    section: {
        type: String,
        default: null,
    },
    dataKey: {
        type: String,
        default: null,
    },
    searchBar: {
        type: Boolean,
        default: true,
    },
    prefix: {
        type: String,
        default: null,
    },
    rightFilter: {
        type: Boolean,
        default: true,
    },
    columns: {
        type: Array,
        default: null,
    },
    arrayDataProps: {
        type: Object,
        default: null,
    },
    redirect: {
        type: Boolean,
        default: true,
    },
    keepData: {
        type: Boolean,
        default: true,
    },
});

const route = useRoute();
let arrayData;
const sectionValue = computed(() => $props.section ?? $props.dataKey);
const isMainSection = computed(() => {
    const isSame = sectionValue.value == route.name;
    if (!isSame && arrayData) {
        arrayData.reset(['userParams', 'userFilter']);
    }
    return isSame;
});
const searchbarId = 'section-searchbar';
const hasContent = useHasContent(`#${searchbarId}`);

onBeforeMount(() => {
    if ($props.dataKey)
        arrayData = useArrayData($props.dataKey, {
            searchUrl: 'table',
            keepData: $props.keepData,
            ...$props.arrayDataProps,
            navigate: $props.redirect,
        });
});
</script>
<template>
    <slot name="searchbar">
        <VnSearchbar
            v-if="searchBar && !hasContent"
            v-bind="arrayDataProps"
            :data-key="dataKey"
            :label="$t(`${prefix}.search`)"
            :info="$t(`${prefix}.searchInfo`)"
        />
        <div :id="searchbarId"></div>
    </slot>
    <RightMenu>
        <template #right-panel v-if="$slots['rightMenu'] || rightFilter">
            <slot name="rightMenu">
                <VnTableFilter
                    v-if="rightFilter && columns"
                    :data-key="dataKey"
                    :array-data="arrayData"
                    :columns="columns"
                />
            </slot>
        </template>
    </RightMenu>
    <slot name="body" v-if="isMainSection" />
    <RouterView v-else />
</template>
