<template>
  <PageHeader />
  <div class="main">
    <div class="manage-tabs">
      <BaseButton
        v-for="tab in MANAGE_TAB_LIST"
        :key="tab.id"
        :text="tab.label"
        :class="{ 'nav-tab-item--active': activeTab === tab.id }"
        @click="switchTab(tab.id)"
      />
    </div>

    <ManageBasicReport v-show="activeTab === 'dashboard'" />
    <ManageBasicArchive v-show="activeTab === 'archive'" />
    <ManageFinanceReport v-show="activeTab === 'audit'" />
    <ManageHistoryQuery v-show="activeTab === 'assets'" />
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import PageHeader from '@/components/layout/PageHeader.vue';
import ManageBasicReport from '@/components/manage/pages/ManageBasicReport.vue';
import ManageBasicArchive from '@/components/manage/pages/ManageBasicArchive.vue';
import ManageFinanceReport from '@/components/manage/pages/ManageFinanceReport.vue';
import ManageHistoryQuery from '@/components/manage/pages/ManageHistoryQuery.vue';
import { useEnterpriseStore } from '@/store/enterprise';
import BaseButton from '@/components/base/BaseButton.vue';
import {
  MANAGE_TAB_LIST,
  buildManageRoute,
  isManageTabId,
  parseManageRoute,
} from '@/utils/manageRoutes';

const route = useRoute();
const router = useRouter();
const enterpriseStore = useEnterpriseStore();

const activeTab = ref('dashboard');

const syncTabFromRoute = () => {
  const { tab } = parseManageRoute(route);
  activeTab.value = isManageTabId(tab) ? tab : 'dashboard';
};

const switchTab = (tabId) => {
  if (!isManageTabId(tabId)) return;
  if (tabId === activeTab.value) return;

  if (tabId === 'audit') {
    router.replace(buildManageRoute({ tab: 'audit', sub: 'pending' }));
    return;
  }

  router.replace(buildManageRoute({ tab: tabId }));
};

watch(() => route.fullPath, syncTabFromRoute, { immediate: true });

onMounted(() => {
  enterpriseStore.fetchList();
});
</script>

<style scoped>
.main {
  width: 100%;
  max-width: var(--page-max-width);
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.manage-tabs {
  width: 100%;
  max-width: var(--content-max-width);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

@media screen and (max-width: 1440px) {
  .main,
  .manage-tabs {
    width: 100%;
    max-width: 1440px;
  }
}
</style>
