<script setup>
import RightAdvancedMenu from './RightAdvancedMenu.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnTableFilter from '../VnTable/VnTableFilter.vue';
import { onBeforeMount, onMounted, onUnmounted, computed, ref } from 'vue';
import { useArrayData } from 'src/composables/useArrayData';
import { useRoute, useRouter } 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();
const router = useRouter();

let arrayData;
const sectionValue = computed(() => $props.section ?? $props.dataKey);
const isMainSection = ref(false);

const searchbarId = 'section-searchbar';
const advancedMenuSlot = 'advanced-menu';
const hasContent = useHasContent(`#${searchbarId}`);

onBeforeMount(() => {
    if ($props.dataKey)
        arrayData = useArrayData($props.dataKey, {
            searchUrl: 'table',
            keepData: $props.keepData,
            ...$props.arrayDataProps,
            navigate: $props.redirect,
        });
    checkIsMain();
});

onMounted(() => {
    const unsubscribe = router.afterEach(() => {
        checkIsMain();
    });
    onUnmounted(unsubscribe);
});

onUnmounted(() => {
    if (arrayData) arrayData.destroy();
});

function checkIsMain() {
    isMainSection.value = sectionValue.value == route.name;
    if (!isMainSection.value && arrayData) {
        arrayData.reset(['userParams', 'filter']);
        arrayData.setCurrentFilter();
    }
}
</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>
    <RightAdvancedMenu :is-main-section="isMainSection">
        <template #advanced-menu v-if="$slots[advancedMenuSlot] || rightFilter">
            <slot :name="advancedMenuSlot">
                <VnTableFilter
                    v-if="rightFilter && columns"
                    :data-key="dataKey"
                    :array-data="arrayData"
                    :columns="columns"
                />
            </slot>
        </template>
    </RightAdvancedMenu>
    <slot name="body" v-if="isMainSection" />
    <RouterView v-else />
</template>
