<template>
  <PageHeader :title="$t('projects')">
    <UiButton
      v-if="!!projects"
      icon="plus"
      href="/projects/create"
    >
      Create a new one
    </UiButton>

    <!--    Временно убрано KITD-527 -->
    <!--    <UiButton -->
    <!--      icon="circle-question" -->
    <!--      type="outlined" -->
    <!--      :color="!!projects ? 'secondary' : 'primary'" -->
    <!--    > -->
    <!--      {{ $t('how_does_it_works') }} -->
    <!--    </UiButton> -->
  </PageHeader>

  <div class="projects-content">
    <ProjectCreate v-if="!projects" />

    <ProjectsTable
      v-else
      class="projects-content__table"
      :projects="projects"
    />

    <ProjectInfoColumns />
  </div>

<!--  Временно убрано KITD-527 -->
<!--  <PageFooterInfoBlock -->
<!--    :title="$t('test_functional')" -->
<!--    :text="$t('learn_functional')" -->
<!--    :action="$t('try')" -->
<!--  /> -->
</template>

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

interface Project {
  id: number
  name: string
  account?: ProjectAccount
}

interface ProjectDetailed {
  id: number
  name: string
  accountIds: number[] | string[]
}

interface ProjectAccount {
  id?: number
  balance: string
}

const { data: projects } = await useAsyncData('projects', async () => {
  const nuxtApp = useNuxtApp()

  const projects = await $api<Project[]>('/online_stores', {
    method: 'get',
  })

  if (!projects)
    return null

  const detailedProjects = await nuxtApp.runWithContext(async () => {
    const promises = await Promise.allSettled(
      projects.map((project) => {
        return $api(`/online_stores/${project.id}`, {
          method: 'get',
        })
      }),
    )

    return (
      promises.filter(
        ({ status }) => status === 'fulfilled',
      ) as PromiseFulfilledResult<ProjectDetailed>[]
    ).map(({ value }) => value)
  })

  const balances = await nuxtApp.runWithContext(async () => {
    const promises = await Promise.allSettled(
      detailedProjects.map((project) => {
        return $api(`/accounts/${project.accountIds[0]}`, {
          method: 'get',
        })
      }),
    )

    return (
      promises.filter(
        ({ status }) => status === 'fulfilled',
      ) as PromiseFulfilledResult<ProjectAccount>[]
    ).map(({ value }) => value)
  })

  return projects.map((project) => {
    const detail = detailedProjects.find(detail => detail.id === project.id)
    let balance

    if (detail)
      balance = balances.find(balance => balance.id === detail.accountIds[0])

    balance ??= { balance: 0 } as unknown as ProjectAccount

    return {
      ...project,
      account: balance,
    }
  })
})
</script>

<style lang="scss">
.projects-content {
  display: grid;
  align-items: flex-start;
  grid-template-columns: auto 270px;
  background-color: $clr-white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 32px;
  gap: 16px;

  &__table {
    align-self: flex-start;
  }
}
</style>
