<script lang="ts" setup>
import { useDateFormat } from '@vueuse/core'

interface Team {
  id: string
  name: string
  logo: string | null
  createdAt: Date
  owner: {
    name: string
  }
  members: Array<{
    id: string
    role: string
    user: {
      id: string
      name: string
      email: string
      avatarUrl?: string
    }
  }>
  subscription?: {
    status: string
  } | null
}

const { data: teams, refresh } = useApiFetch<Team[]>('/api/super-admin/teams')
const columns = computed(() => [
  t('admin.organizationsPage.columns.name'),
  t('admin.organizationsPage.columns.owner'),
  t('admin.organizationsPage.columns.members'),
  t('admin.organizationsPage.columns.subscription'),
  t('admin.organizationsPage.columns.createdAt')
])

const { t } = useI18n()
const localePath = useLocalePath()

definePageMeta({
  layout: 'dashboard',
  middleware: ['super-admin'],
  colorMode: 'light'
})
</script>

<template>
  <NuxtLayout
    :page-title="t('admin.organizations')"
    :parent="{
      label: t('admin.title'),
      to: localePath('/dashboard/admin')
    }"
    type="admin"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refresh" />
      <UCard>
        <div class="overflow-x-auto">
          <table class="w-full table-auto text-left text-sm">
            <thead>
              <tr>
                <th
                  v-for="column in columns"
                  :key="column"
                  class="p-2 text-nowrap whitespace-nowrap"
                >
                  {{ column }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="team in (teams ?? [])"
                :key="team.id"
                class="border-b border-neutral-100 text-sm text-neutral-500 hover:bg-neutral-50 dark:border-white/10 dark:text-neutral-400 dark:hover:bg-neutral-800/50 [&>td]:whitespace-nowrap"
              >
                <td class="p-2">
                  <div class="flex items-center gap-2">
                    <UAvatar
                      :src="team.logo ?? undefined"
                      size="2xs"
                      :alt="team.name"
                    />
                    {{ team.name }}
                  </div>
                </td>
                <td class="p-2">
                  {{ team.owner.name }}
                </td>
                <td class="p-2">
                  <SuperAdminTeamMembers :members="team.members" />
                </td>
                <td class="p-2">
                  {{ team.subscription?.status ?? '-' }}
                </td>
                <td class="p-2">
                  {{ useDateFormat(team.createdAt, 'DD/MM/YYYY').value }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </UCard>
    </UPageBody>
  </NuxtLayout>
</template>
