<template>
  <PageHeader
    :title="project.name"
    with-back-button
  >
    <div class="project-header">
      <MoneyAmount
        class="project-header__balance"
        :value="account.balance"
        currency="USDT"
      />

      <UiButton
        icon="s-restore"
        size="small"
        type="outlined"
        color="secondary"
        :loading="accountPending"
        @click="accountRefresh()"
      />
    </div>
  </PageHeader>

  <UiTabs v-model="activeTab" class="mb-16" :options="tabs" />

  <NuxtPage />
</template>

<script setup lang="ts">
definePageMeta({
  middleware: ['auth'],
})

const router = useRouter()
const route = useRoute()

const activeTab = ref(route.path)

const { data: project } = await useAsyncData('project', () => {
  return $api(`/online_stores/${route.params.projectId}`, {
    method: 'get',
  })
})

if (!project.value) {
  throw createError({
    statusCode: 404,
    statusMessage: 'Page Not Found',
  })
}

const {
  data: account,
  refresh: accountRefresh,
  pending: accountPending,
} = await useAsyncData('account', () =>
  $api(`/accounts/${project.value.accountIds[0]}`, {
    method: 'get',
  }))

const intervalId = setInterval(() => refreshNuxtData(['invoices', 'transactions', 'account']), 30000)

const tabs = computed(() => [
  {
    label: 'Assets',
    value: `/projects/${route.params.projectId}`,
  },
  {
    label: 'Invoices',
    value: `/projects/${route.params.projectId}/invoices`,
  },
  {
    label: 'Transactions',
    value: `/projects/${route.params.projectId}/transactions`,
  },
])

watch(activeTab, (value) => {
  router.push(value)
})

onUnmounted(() => clearInterval(intervalId))
</script>

<style lang="scss">
.project-header {
  display: flex;
  align-items: center;
  gap: 8px;

  &__balance {
    @include h2('money-amount-value', true);

    color: $clr-grey-500;
  }
}
</style>
